1 What Does a Controller Do?
Action Controller is the C in MVC. After the router has determined which controller to use for a request, the 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 middleman 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 user data to the model.
For more details on the routing process, see Rails Routing from the Outside In.
2 Controller Naming Convention
The naming convention of controllers in Rails favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. ApplicationController
). For example, ClientsController
is preferable to ClientController
, SiteAdminsController
is preferable to SiteAdminController
or SitesAdminsController
, and so on.
Following this convention will allow you to use the default route generators (e.g. resources
, etc) without needing to qualify each :path
or :controller
, and will keep named route helpers' usage consistent throughout your application. See Layouts and Rendering Guide for more details.
The controller naming convention differs from the naming convention of models, which are expected to be named in singular form.
3 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.
class ClientsController < ApplicationController
def new
end
end
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 call its new
method. Note that the empty method from the example above would work just fine because Rails will by default render the new.html.erb
view unless the action says otherwise. By creating a new Client
, the new
method can make a @client
instance variable accessible in the view:
def new
@client = Client.new
end
The Layouts and 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 (with private
or protected
) which are not intended to be actions, like auxiliary methods or filters.
Some method names are reserved by Action Controller. Accidentally redefining them as actions, or even as auxiliary methods, could result in SystemStackError
. If you limit your controllers to only RESTful Resource Routing actions you should not need to worry about this.
If you must use a reserved method as an action name, one workaround is to use a custom route to map the reserved method name to your non-reserved action method.
4 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 HTTP POST 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:
class ClientsController < ApplicationController
# This action uses query string parameters because it gets run
# by an HTTP GET request, but this does not make any difference
# to how the parameters are accessed. The URL for
# this action would look like this to list activated
# clients: /clients?status=activated
def index
if params[:status] == "activated"
@clients = Client.activated
else
@clients = Client.inactivated
end
end
# This action uses POST parameters. They are most likely coming
# from an HTML form that the user has submitted. The URL for
# this RESTful request will be "/clients", and the data will be
# sent as part of the request body.
def create
@client = Client.new(params[:client])
if @client.save
redirect_to @client
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
render "new"
end
end
end
4.1 Hash and Array Parameters
The params
hash is not limited to one-dimensional keys and values. It can contain nested arrays and hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
GET /clients?ids[]=1&ids[]=2&ids[]=3
The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3" as the "[" and "]" characters are not allowed in URLs. Most of the time you don't have to worry about this because the browser will encode it for you, and Rails will decode it automatically, but if you ever find yourself having to send those requests to the server manually you should keep this in mind.
The value of params[:ids]
will now be ["1", "2", "3"]
. Note that parameter values are always strings; Rails does not attempt to guess or cast the type.
Values such as [nil]
or [nil, nil, ...]
in params
are replaced
with []
for security reasons by default. See Security Guide
for more information.
To send a hash, you include the key name inside the brackets:
<form accept-charset="UTF-8" action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
<input type="text" name="client[address][city]" value="Carrot City" />
</form>
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]
.
The params
object acts like a Hash, but lets you use symbols and strings interchangeably as keys.
4.2 JSON Parameters
If your application exposes an API, you are likely to be accepting parameters in JSON format. If the "Content-Type" header of your request is set to "application/json", Rails will automatically load your parameters into the params
hash, which you can access as you would normally.
So for example, if you are sending this JSON content:
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
Your controller will receive params[:company]
as { "name" => "acme", "address" => "123 Carrot Street" }
.
Also, if you've turned on config.wrap_parameters
in your initializer or called wrap_parameters
in your controller, you can safely omit the root element in the JSON parameter. In this case, the parameters will be cloned and wrapped with a key chosen based on your controller's name. So the above JSON request can be written as:
{ "name": "acme", "address": "123 Carrot Street" }
And, assuming that you're sending the data to CompaniesController
, it would then be wrapped within the :company
key like this:
{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }
You can customize the name of the key or specific parameters you want to wrap by consulting the API documentation
Support for parsing XML parameters has been extracted into a gem named actionpack-xml_parser
.
4.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 that captures the :status
parameter in a "pretty" URL:
get '/clients/:status', to: 'clients#index', foo: 'bar'
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", as if it were passed in the query string. Your controller will also receive params[:action]
as "index" and params[:controller]
as "clients".
4.4 Composite Key Parameters
Composite key parameters contain multiple values in one parameter. For this reason, we need to be able to extract each value and pass them to Active Record. We can leverage the extract_value
method for this use-case.
Given the following controller:
class BooksController < ApplicationController
def show
# Extract the composite ID value from URL parameters.
id = params.extract_value(:id)
# Find the book using the composite ID.
@book = Book.find(id)
# use the default rendering behaviour to render the show view.
end
end
And the following route:
get '/books/:id', to: 'books#show'
When a user opens the URL /books/4_2
, the controller will extract the composite
key value ["4", "2"]
and pass it to Book.find
to render the right record in the view.
The extract_value
method may be used to extract arrays out of any delimited parameters.
4.5 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:
class ApplicationController < ActionController::Base
def default_url_options
{ locale: I18n.locale }
end
end
These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed to url_for
calls.
If you define default_url_options
in ApplicationController
, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.
In a given request, the method is not actually called for every single generated URL. For performance reasons, the returned hash is cached, and there is at most one invocation per request.
4.6 Strong Parameters
With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been permitted. This means that you'll have to make a conscious decision about which attributes to permit for mass update. This is a better security practice to help prevent accidentally allowing users to update sensitive model attributes.
In addition, parameters can be marked as required and will flow through a predefined raise/rescue flow that will result in a 400 Bad Request being returned if not all required parameters are passed in.
class PeopleController < ActionController::Base
# This will raise an ActiveModel::ForbiddenAttributesError exception
# because it's using mass assignment without an explicit permit
# step.
def create
Person.create(params[:person])
end
# This will pass with flying colors as long as there's a person key
# in the parameters, otherwise it'll raise an
# ActionController::ParameterMissing exception, which will get
# caught by ActionController::Base and turned into a 400 Bad
# Request error.
def update
person = current_account.people.find(params[:id])
person.update!(person_params)
redirect_to person
end
private
# Using a private method to encapsulate the permissible parameters
# is just a good pattern since you'll be able to reuse the same
# permit list between create and update. Also, you can specialize
# this method with per-user checking of permissible attributes.
def person_params
params.require(:person).permit(:name, :age)
end
end
4.6.1 Permitted Scalar Values
Calling permit
like:
params.permit(:id)
permits the specified key (:id
) for inclusion if it appears in params
and
it has a permitted scalar value associated. Otherwise, the key is going
to be filtered out, so arrays, hashes, or any other objects cannot be
injected.
The permitted scalar types are String
, Symbol
, NilClass
,
Numeric
, TrueClass
, FalseClass
, Date
, Time
, DateTime
,
StringIO
, IO
, ActionDispatch::Http::UploadedFile
, and
Rack::Test::UploadedFile
.
To declare that the value in params
must be an array of permitted
scalar values, map the key to an empty array:
params.permit(id: [])
Sometimes it is not possible or convenient to declare the valid keys of a hash parameter or its internal structure. Just map to an empty hash:
params.permit(preferences: {})
but be careful because this opens the door to arbitrary input. In this
case, permit
ensures values in the returned structure are permitted
scalars and filters out anything else.
To permit an entire hash of parameters, the permit!
method can be
used:
params.require(:log_entry).permit!
This marks the :log_entry
parameters hash and any sub-hash of it as
permitted and does not check for permitted scalars, anything is accepted.
Extreme care should be taken when using permit!
, as it will allow all current
and future model attributes to be mass-assigned.
4.6.2 Nested Parameters
You can also use permit
on nested parameters, like:
params.permit(:name, { emails: [] },
friends: [ :name,
{ family: [ :name ], hobbies: [] }])
This declaration permits the name
, emails
, and friends
attributes. It is expected that emails
will be an array of permitted
scalar values, and that friends
will be an array of resources with
specific attributes: they should have a name
attribute (any
permitted scalar values allowed), a hobbies
attribute as an array of
permitted scalar values, and a family
attribute which is restricted
to having a name
(any permitted scalar values allowed here, too).
4.6.3 More Examples
You may want to also use the permitted attributes in your new
action. This raises the problem that you can't use require
on the
root key because, normally, it does not exist when calling new
:
# using `fetch` you can supply a default and use
# the Strong Parameters API from there.
params.fetch(:blog, {}).permit(:title, :author)
The model class method accepts_nested_attributes_for
allows you to
update and destroy associated records. This is based on the id
and _destroy
parameters:
# permit :id and :_destroy
params.require(:author).permit(:name, books_attributes: [:title, :id, :_destroy])
Hashes with integer keys are treated differently, and you can declare
the attributes as if they were direct children. You get these kinds of
parameters when you use accepts_nested_attributes_for
in combination
with a has_many
association:
# To permit the following data:
# {"book" => {"title" => "Some Book",
# "chapters_attributes" => { "1" => {"title" => "First Chapter"},
# "2" => {"title" => "Second Chapter"}}}}
params.require(:book).permit(:title, chapters_attributes: [:title])
Imagine a scenario where you have parameters representing a product name, and a hash of arbitrary data associated with that product, and you want to permit the product name attribute and also the whole data hash:
def product_params
params.require(:product).permit(:name, data: {})
end
4.6.4 Outside the Scope of Strong Parameters
The strong parameter API was designed with the most common use cases in mind. It is not meant as a silver bullet to handle all of your parameter filtering problems. However, you can easily mix the API with your own code to adapt to your situation.
5 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 several of different storage mechanisms:
ActionDispatch::Session::CookieStore
- Stores everything on the client.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 usingCacheStore
instead).ActionDispatch::Session::ActiveRecordStore
- Stores the data in a database using Active Record (requires theactiverecord-session_store
gem)- A custom store or a store provided by a third party gem
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 to use the session. The cookie data is cryptographically signed to make it tamper-proof. And it is also encrypted so anyone with access to it can't read its contents. (Rails will not accept it if it has been edited).
The CookieStore can store around 4 kB 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 (such as 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 an initializer:
Rails.application.config.session_store :cache_store
See config.session_store
in the
configuration guide for more information.
Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer:
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_your_app_session'
You can also pass a :domain
key and specify the domain name for the cookie:
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
Rails sets up (for the CookieStore) a secret key used for signing the session data in config/credentials.yml.enc
. This can be changed with bin/rails credentials:edit
.
# aws:
# access_key_id: 123
# secret_access_key: 345
# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 492f...
Changing the secret_key_base when using the CookieStore
will invalidate all existing sessions.
5.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:
class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key
# :current_user_id This is a common way to handle user login in
# a Rails application; logging in sets the session value and
# logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by(id: session[:current_user_id])
end
end
To store something in the session, just assign it to the key like a hash:
class LoginsController < ApplicationController
# "Create" a login, aka "log the user in"
def create
if user = User.authenticate(params[:username], params[:password])
# Save the user ID in the session so it can be used in
# subsequent requests
session[:current_user_id] = user.id
redirect_to root_url
end
end
end
To remove something from the session, delete the key/value pair:
class LoginsController < ApplicationController
# "Delete" a login, aka "log the user out"
def destroy
# Remove the user id from the session
session.delete(:current_user_id)
# Clear the memoized current user
@_current_user = nil
redirect_to root_url, status: :see_other
end
end
To reset the entire session, use reset_session
.
5.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 passing error messages, etc.
The flash is accessed via the flash
method. Like the session, the flash is represented as 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:
class LoginsController < ApplicationController
def destroy
session.delete(:current_user_id)
flash[:notice] = "You have successfully logged out."
redirect_to root_url, status: :see_other
end
end
Note that it is also possible to assign a flash message as part of the redirection. You can assign :notice
, :alert
or the general-purpose :flash
:
redirect_to root_url, notice: "You have successfully logged out."
redirect_to root_url, alert: "You're stuck here!"
redirect_to root_url, flash: { referral_code: 1234 }
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 any error alerts or notices from the flash in the application's layout:
<html>
<!-- <head/> -->
<body>
<% flash.each do |name, msg| -%>
<%= content_tag :div, msg, class: name %>
<% end -%>
<!-- more content -->
</body>
</html>