This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
- Rails Generate Custom Secret Key West
- Rails Generate Custom Secret Key Chain
- Rails Generate Secret
- Rails Generate Custom Secret Key Generator
Dec 18, 2012 Recently I had to build one Rails app off a clone of another Rails app. I wanted to find a quick way to change the secret token in config/initializers/secrettoken.rb. Action Controller Overview. Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer. Rails sets up (for the CookieStore) a secret key used for signing the session data in config/credentials.yml.enc.
1 Command Line Basics
There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
rails console
rails server
rails test
rails generate
rails db:migrate
rails db:create
rails routes
rails dbconsole
rails new app_name
You can get a list of rails commands available to you, which will often depend on your current directory, by typing
rails --help
. Each command has a description, and should help you find the thing you need.Let's create a simple Rails application to step through each of these commands in context.
1.1 rails new
The first thing we'll want to do is create a new Rails application by running the
rails new
command after installing Rails.You can install the rails gem by typing
gem install rails
, if you don't have it already.Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
1.2 rails server
The
rails server
command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.With no further work,
rails server
will run our new shiny Rails app:With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open http://localhost:3000, you will see a basic Rails app running.
You can also use the alias 's' to start the server:
rails s
.The server can be run on a different port using the
-p
option. The default development environment can be changed using -e
.The
-b
option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a -d
option.1.3 rails generate
The
rails generate
command uses templates to create a whole lot of things. Running rails generate
by itself gives a list of available generators:You can also use the alias 'g' to invoke the generator command:
rails g
.You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
Using generators will save you a large amount of time by writing boilerplate code, code that is necessary for the app to work.
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
All Rails console utilities have help text. As with most *nix utilities, you can try adding
--help
or -h
to the end, for example rails server --help
.The controller generator is expecting parameters in the form of
generate controller ControllerName action1 action2
. Let's make a Greetings
controller with an action of hello, which will say something nice to us.What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file, and a stylesheet file.
Check out the controller and modify it a little (in
app/controllers/greetings_controller.rb
):Then the view, to display our message (in
app/views/greetings/hello.html.erb
):Fire up your server using
rails server
.The URL will be http://localhost:3000/greetings/hello.
With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the index action of that controller.
Rails comes with a generator for data models too.
For a list of available field types for the
type
parameter, refer to the API documentation for the add_column method for the SchemaStatements
module. The index
parameter generates a corresponding index for the column.But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
We will set up a simple resource called 'HighScore' that will keep track of our highest score on video games we play.
The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the
high_scores
table and fields), takes care of the route for the resource, and new tests for everything.The migration requires that we migrate, that is, run some Ruby code (living in that
20130717151933_create_high_scores.rb
) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the rails db:migrate
command. We'll talk more about that command below.Let's talk about unit tests. Unit tests are code that tests and makes assertionsabout code. In unit testing, we take a little part of code, say a method of a model,and test its inputs and outputs. Unit tests are your friend. The sooner you makepeace with the fact that your quality of life will drastically increase when you unittest your code, the better. Seriously. Please visitthe testing guide for an in-depthlook at unit testing.
Let's see the interface Rails created for us.
Go to your browser and open http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)
1.4 rails console
The
console
command lets you interact with your Rails application from the command line. On the underside, rails console
uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.You can also use the alias 'c' to invoke the console:
rails c
.You can specify the environment in which the
console
command should operate.If you wish to test out some code without changing any data, you can do that by invoking
rails console --sandbox
.1.4.1 The app and helper objects
Inside the
rails console
you have access to the app
and helper
instances.With the
app
method you can access named route helpers, as well as do requests.With the
helper
method it is possible to access Rails and your application's helpers.1.5 rails dbconsole
rails dbconsole
figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL (including MariaDB), PostgreSQL, and SQLite3.You can also use the alias 'db' to invoke the dbconsole:
rails db
.1.6 rails runner
runner
runs Ruby code in the context of Rails non-interactively. For instance:You can also use the alias 'r' to invoke the runner:
rails r
.You can specify the environment in which the
runner
command should operate using the -e
switch.You can even execute ruby code written in a file with runner.
1.7 rails destroy
Think of
destroy
as the opposite of generate
. It'll figure out what generate did, and undo it.You can also use the alias 'd' to invoke the destroy command:
rails d
.1.8 rails about
rails about
gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.1.9 rails assets:
You can precompile the assets in
app/assets
using rails assets:precompile
, and remove older compiled assets using rails assets:clean
. The assets:clean
command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.If you want to clear
public/assets
completely, you can use rails assets:clobber
.1.10 rails db:
The most common commands of the
db:
rails namespace are migrate
and create
, and it will pay off to try out all of the migration rails commands (up
, down
, redo
, reset
). rails db:version
is useful when troubleshooting, telling you the current version of the database.More information about migrations can be found in the Migrations guide.
1.11 rails notes
rails notes
searches through your code for comments beginning with a specific keyword. You can refer to rails notes --help
for information about usage.By default, it will search in
app
, config
, db
, lib
, and test
directories for FIXME, OPTIMIZE, and TODO annotations in files with extension .builder
, .rb
, .rake
, .yml
, .yaml
, .ruby
, .css
, .js
, and .erb
.1.11.1 Annotations
You can pass specific annotations by using the
--annotations
argument. By default, it will search for FIXME, OPTIMIZE, and TODO.Note that annotations are case sensitive.1.11.2 Tags
You can add more default tags to search for by using
config.annotations.register_tags
. It receives a list of tags.1.11.3 Directories
You can add more default directories to search from by using
config.annotations.register_directories
. It receives a list of directory names.1.11.4 Extensions
You can add more default file extensions to search from by using
config.annotations.register_extensions
. It receives a list of extensions with its corresponding regex to match it up.1.12 rails routes
rails routes
Generate a new ssh key and delete old. will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.1.13 rails test
A good description of unit testing in Rails is given in A Guide to Testing Rails Applications
Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the
test:
namespace helps in running the different tests you will hopefully write.1.14 rails tmp:
The
Rails.root/tmp
directory is, like the *nix /tmp directory, the holding place for temporary files like process id files and cached actions.The
tmp:
namespaced commands will help you clear and create the Rails.root/tmp
directory:rails tmp:cache:clear
clearstmp/cache
.rails tmp:sockets:clear
clearstmp/sockets
.rails tmp:screenshots:clear
clearstmp/screenshots
.rails tmp:clear
clears all cache, sockets, and screenshot files.rails tmp:create
creates tmp directories for cache, sockets, and pids.
1.15 Miscellaneous
rails stats
is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.rails secret
will give you a pseudo-random key to use for your session secret.rails time:zones:all
lists all the timezones Rails knows about.
1.16 Custom Rake Tasks
Custom rake tasks have a
.rake
extension and are placed inRails.root/lib/tasks
. You can create these custom rake tasks with therails generate task
command.To pass arguments to your custom rake task:
You can group tasks by placing them in namespaces:
Invocation of the tasks will look like:
If you need to interact with your application models, perform database queries, and so on, your task should depend on the
environment
task, which will load your application code.2 The Rails Advanced Command Line
More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
2.1 Rails with Databases and SCM
When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.
Let's see what a
--git
option and a --database=postgresql
option will do for us:We had to create the gitapp directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
It also generated some lines in our
database.yml
configuration corresponding to our choice of PostgreSQL for database.The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the
rails new
command to generate the basis of your app.Feedback
You're encouraged to help improve the quality of this guide.
Please contribute if you see any typos or factual errors. To get started, you can read our documentation contributions section.
You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for master. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the master branch. Check the Ruby on Rails Guides Guidelines for style and conventions.
If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.
And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list.
1 What Does a Controller Do?
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that’s not a problem, this is just the most common way for a controller to work.
A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
For more details on the routing process, see Rails Routing from the Outside In.
2 Methods and Actions
A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
As an example, if a user goes to /clients/new in your application to add a new client, Rails will create an instance of ClientsController and run the new method. Note that the empty method from the example above could work just fine because Rails will by default render the new.html.erb view unless the action says otherwise. The new method could make available to the view a @client instance variable by creating a new Client:
The Layouts & Rendering Guide explains this in more detail.
ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you’re curious to see what’s in there, you can see all of them in the API documentation or in the source itself.
Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
3 Parameters
You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after “?” in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It’s called POST data because it can only be sent as part of an HTTPPOST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller:
3.1 Hash and Array Parameters
The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets “[]” to the key name:
The actual URL in this example will be encoded as “/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3” as “[” and “]” are not allowed in URLs. Most of the time you don’t have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
The value of params[:ids] will now be ['1', '2', '3']. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
To send a hash you include the key name inside the brackets:
When this form is submitted, the value of params[:client] will be {'name' => “Acme”, “phone” => “12345”, “address” => {'postcode' => “12345”, “city” => “Carrot City”}}. Note the nested hash in params[:client][:address].
Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
3.2 JSON/XML parameters
If you’re writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into params hash, which you’ll be able to access like you would normally do with form data.
So for example, if you are sending this JSON parameter:
You’ll get params[:company] as { :name => “acme”, “address” => “123 Carrot Street” }.
Also, if you’ve turned on config.wrap_parameters in your initializer or calling wrap_parameters in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller’s name by default. So the above parameter can be written as: https://ykerbgg.weebly.com/issues-of-key-pair-generation.html.
And assume that you’re sending the data to CompaniesController, it would then be wrapped in :company key like this:
You can customize the name of the key or specific parameters you want to wrap by consulting the API documentation
3.3 Routing Parameters
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values. Any other parameters defined by the routing, such as :id will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the :status parameter in a “pretty” URL:
In this case, when a user opens the URL/clients/active, params[:status] will be set to “active”. When this route is used, params[:foo] will also be set to “bar” just like it was passed in the query string. In the same way params[:action] will contain “index”.
3.4 default_url_options
You can set global default parameters for URL generation by defining a method called default_url_options in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
These options will be used as a starting point when generating URLs, so it’s possible they’ll be overridden by the options passed in url_for calls.
If you define default_url_options in ApplicationController, as in the example above, it would be used for all URL generation. The method can also be defined in one specific controller, in which case it only affects URLs generated there.
4 Session
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
- ActionDispatch::Session::CookieStore – Stores everything on the client.
- ActiveRecord::SessionStore – Stores the data in a database using Active Record.
- ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.
- ActionDispatch::Session::MemCacheStore – Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store – the CookieStore – which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
The CookieStore can store around 4kB of data — much less than the others — but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
If your user sessions don’t store critical data or don’t need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
Read more about session storage in the Security Guide.
If you need a different session storage mechanism, you can change it in the config/initializers/session_store.rb file:
Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in config/initializers/session_store.rb:
You can also pass a :domain key and specify the domain name for the cookie:
Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in config/initializers/secret_token.rb
Changing the secret when using the CookieStore will invalidate all existing sessions.
4.1 Accessing the Session
In your controller you can access the session through the session instance method.
Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
Session values are stored using key/value pairs like a hash:
To store something in the session, just assign it to the key like a hash:
To remove something from the session, assign that key to be nil:
To reset the entire session, use reset_session.
4.2 The Flash
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let’s use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
Note it is also possible to assign a flash message as part of the redirection.
The destroy action redirects to the application’s root_url, where the message will be displayed. Note that it’s entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It’s conventional to display eventual errors or notices from the flash in the application’s layout:
This way, if an action sets an error or a notice message, the layout will display it automatically.
If you want a flash value to be carried over to another request, use the keep method:
4.2.1 flash.now
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:
5 Cookies
Your application can store small amounts of data on the client — called cookies — that will be persisted across requests and even sessions. Rails provides easy access to cookies via the cookies method, which — much like the session — works like a hash:
Note that while for session values you set the key to nil, to delete a cookie value you should use cookies.delete(:key).
6 Rendering xml and json data
ActionController makes it extremely easy to render xml or json Free office 365 product key 2019. data. If you generate a controller using scaffold then your controller would look something like this.
Notice that in the above case code is render :xml => @users and not render :xml => @users.to_xml. That is because if the input is not string then rails automatically invokes to_xml .
7 Filters
Filters are methods that are run before, after or “around” a controller action.
Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.
Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
In this example the filter is added to ApplicationController and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn’t be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter:
Now, the LoginsController’s new and create actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
7.1 After Filters and Around Filters
In addition to before filters, you can also run filters after an action has been executed, or both before and after.
After filters are similar to before filters, but because the action has already been run they have access to the response data that’s about to be sent to the client. Obviously, after filters cannot stop the action from running.
Around filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview.
They can choose not to yield and build the response themselves, in which case the action is not run.
7.2 Other Ways to Use Filters
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the require_login filter from above could be rewritten to use a block:
Note that the filter in this case uses send because the logged_in? method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
Again, this is not an ideal example for this filter, because it’s not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method filter which gets run before or after the action, depending on if it’s a before or after filter. Classes used as around filters can also use the same filter method, which will get run in the same way. The method must yield to execute the action. Alternatively, it can have both a before and an after method that are run before and after the action.
8 Request Forgery Protection
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user’s knowledge or permission.
The first step to avoid this is to make sure all “destructive” actions (create, update and destroy) can only be accessed with non-GET requests. If you’re following RESTful conventions you’re already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that’s where the request forgery protection comes in. As the name says, it protects from forged requests.
The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
If you generate a form like this:
You will see how the token gets added as a hidden field:
Rails adds this token to every form that’s generated using the form helpers, so most of the time you don’t have to worry about it. If you’re writing a form manually or need to add the token for another reason, it’s available through the method form_authenticity_token:
The form_authenticity_token generates a valid authentication token. That’s useful in places where Rails does not add it automatically, like in custom Ajax calls.
The Security Guide has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
9 The Request and Response Objects
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The request method contains an instance of AbstractRequest and the response method returns a response object representing what is going to be sent back to the client.
9.1 The request Object
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the API documentation. Among the properties that you can access on this object are:
Property of request | Purpose |
---|---|
host | The hostname used for this request. |
domain(n=2) | The hostname’s first n segments, starting from the right (the TLD). |
format | The content type requested by the client. |
method | The HTTP method used for the request. |
get?, post?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD. |
headers | Returns a hash containing the headers associated with the request. |
port | The port number (integer) used for the request. |
protocol | Returns a string containing the protocol used plus “://”, for example “http://”. |
query_string | The query string part of the URL, i.e., everything after “?”. |
remote_ip | The IP address of the client. |
url | The entire URL used for the request. |
9.1.1 path_parameters, query_parameters, and request_parameters
Rails collects all of the parameters sent along with the request in the params hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The query_parameters hash contains parameters that were sent as part of the query string while the request_parameters hash contains parameters sent as part of the post body. The path_parameters hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
9.2 The response Object
The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes – like in an after filter – it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
Property of response | Purpose |
---|---|
body | This is the string of data being sent back to the client. This is most often HTML. |
status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
location | The URL the client is being redirected to, if any. |
content_type | The content type of the response. |
charset | The character set being used for the response. Default is “utf-8”. |
headers | Headers used for the response. |
![Custom Custom](/uploads/1/3/3/9/133906123/397993200.jpg)
9.2.1 Setting Custom Headers
If you want to set custom headers for a response then response.headers is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to response.headers this way:
10 HTTP Authentications
Rails Generate Custom Secret Key West
Rails comes with two built-in HTTP authentication mechanisms:
- Basic Authentication
- Digest Authentication
10.1 HTTP Basic Authentication
HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser’s HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, http_basic_authenticate_with.
With this in place, you can create namespaced controllers that inherit from AdminController. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
10.2 HTTP Digest Authentication
HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, authenticate_or_request_with_http_digest.
As seen in the example above, the authenticate_or_request_with_http_digest block takes only one argument – the username. And the block returns the password. Returning false or nil from the authenticate_or_request_with_http_digest will cause authentication failure.
11 Streaming and File Downloads
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the send_data and the send_file methods, which will both stream data to the client. send_file is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use send_data:
The download_pdf action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the :disposition option to “inline”. The opposite and default value for this option is “attachment”.
11.1 Sending Files
If you want to send a file that already exists on disk, use the send_file method.
This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the :stream option or adjust the block size with the :buffer_size option.
If :type is not specified, it will be guessed from the file extension specified in :filename. If the content type is not registered for the extension, application/octet-stream will be used.
Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
11.2 RESTful Downloads
While send_data works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing “RESTful downloads”. Here’s how you can rewrite the example so that the PDF download is a part of the show action, without any streaming:
In order for this example to work, you have to add the PDFMIME type to Rails. This can be done by adding the following line to the file config/initializers/mime_types.rb:
Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect. What key on piano generator.
Now the user can request to get a PDF version of a client just by adding “.pdf” to the URL:
12 Parameter Filtering
Rails keeps a log file for each environment in the log folder. These are extremely useful when debugging what’s actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to config.filter_parameters in the application configuration. These parameters will be marked [FILTERED] in the log.
13 Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception.
Rails’ default exception handling displays a “500 Server Error” message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple “500 Server Error” message to the user, or a “404 Not Found” if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they’re displayed to the user. There are several levels of exception handling available in a Rails application:
13.1 The Default 500 and 404 Templates
By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the public folder, in 404.html and 500.html respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can’t use RHTML or layouts in them, just plain HTML.
13.2 rescue_from
If you want to do something a bit more elaborate when catching errors, you can use rescue_from, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.
Here’s how you can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.
Of course, this example is anything but elaborate and doesn’t improve on the default exception handling at all, but once you can catch all those exceptions you’re free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn’t have access to a certain section of your application:
Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik’s article on the subject for more information.
14 Force HTTPS protocol
Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use force_ssl method in your controller to enforce that:
Just like the filter, you could also passing :only and :except to enforce the secure connection only to specific actions.
Please note that if you found yourself adding force_ssl to many controllers, you may found yourself wanting to force the whole application to use HTTPS instead. In that case, you can set the config.force_ssl in your environment file.
Feedback
Rails Generate Custom Secret Key Chain
You're encouraged to help improve the quality of this guide.
Rails Generate Secret
If you see any typos or factual errors you are confident to patch, please clone the rails repository and open a new pull request. You can also ask for commit rights on docrails if you plan to submit several patches. Commits are reviewed, but that happens after you've submitted your contribution. This repository is cross-merged with master periodically.
You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Check the Ruby on Rails Guides Guidelines for style and conventions.
If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.
Rails Generate Custom Secret Key Generator
And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the rubyonrails-docs mailing list.