- 1.0.0 (0)
- 1.1.6 (-38)
- 1.2.6 (-1)
- 2.0.3 (5)
- 2.1.0 (2)
- 2.2.1 (0)
- 2.3.8 (1)
- 3.0.0 (-8)
- 3.0.9 (-6)
- 3.1.0 (9)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (-15)
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (1)
- 5.1.7 (1)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (3)
- 7.1.3.4 (0)
- What's this?
Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either render a template or redirect to another action. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.
A sample controller could look like this:
class GuestBookController < ActionController::Base def index @entries = Entry.find(:all) end def sign Entry.create(params[:entry]) redirect_to :action => "index" end end
Actions, by default, render a template in the app/views directory corresponding to the name of the controller and action after executing code in the action. For example, the index action of the GuestBookController would render the template app/views/guestbook/index.rhtml by default after populating the @entries instance variable.
Unlike index, the sign action will not render a template. After performing its main purpose (creating a new entry in the guest book), it initiates a redirect instead. This redirect works by returning an external "302 Moved" HTTP response that takes the user to the index action.
The index and sign represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect. Most actions are variations of these themes.
Requests
Requests are processed by the Action Controller framework by extracting the value of the "action" key in the request parameters. This value should hold the name of the action to be performed. Once the action has been identified, the remaining request parameters, the session (if one is available), and the full request with all the http headers are made available to the action through instance variables. Then the action is performed.
The full request object is available with the request accessor and is primarily used to query for http headers. These queries are made by accessing the environment hash, like this:
def server_ip location = request.env["SERVER_ADDR"] render :text => "This server hosted at #{location}" end
Parameters
All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method which returns a hash. For example, an action that was performed through /weblog/list?category=All&limit=5 will include { "category" => "All", "limit" => 5 } in params.
It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
<input type="text" name="post[name]" value="david"> <input type="text" name="post[address]" value="hyacintvej">
A request stemming from a form holding these inputs will include { "post" => { "name" => "david", "address" => "hyacintvej" } }. If the address input had been named "post[address][street]", the params would have included { "post" => { "address" => { "street" => "hyacintvej" } } }. There's no limit to the depth of the nesting.
Sessions
Sessions allows you to store objects in between requests. This is useful for objects that are not yet ready to be persisted, such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely they could be changed unknowingly. It's usually too much work to keep it all synchronized — something databases already excel at.
You can place objects in the session by using the session method, which accesses a hash:
session[:person] = Person.authenticate(user_name, password)
And retrieved again through the same hash:
Hello #{session[:person]}
For removing objects from the session, you can either assign a single key to nil, like session[:person] = nil, or you can remove the entire session with reset_session.
By default, sessions are stored on the file system in RAILS_ROOT/tmp/sessions. Any object can be placed in the session (as long as it can be Marshalled). But remember that 1000 active sessions each storing a 50kb object could lead to a 50MB store on the filesystem. In other words, think carefully about size and caching before resorting to the use of the session on the filesystem.
An alternative to storing sessions on disk is to use ActiveRecordStore to store sessions in your database, which can solve problems caused by storing sessions in the file system and may speed up your application. To use ActiveRecordStore, uncomment the line:
config.action_controller.session_store = :active_record_store
in your environment.rb and run rake db:sessions:create.
Responses
Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response object is generated automatically through the use of renders and redirects and requires no user intervention.
Renders
Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering of a template. Included in the Action Pack is the Action View, which enables rendering of ERb templates. It's automatically configured. The controller passes objects to the view by assigning instance variables:
def show @post = Post.find(params[:id]) end
Which are then automatically available to the view:
Title: <%= @post.title %>
You don't have to rely on the automated rendering. Especially actions that could result in the rendering of different templates will use the manual rendering methods:
def search @results = Search.find(params[:query]) case @results when 0 then render :action => "no_results" when 1 then render :action => "show" when 2..10 then render :action => "show_many" end end
Read more about writing ERb and Builder templates in ActionView::Base
Redirects
Redirects are used to move from one action to another. For example, after a create action, which stores a blog entry to a database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're going to reuse (and redirect to) a show action that we'll assume has already been created. The code might look like this:
def create @entry = Entry.new(params[:entry]) if @entry.save # The entry was saved correctly, redirect to show redirect_to :action => 'show', :id => @entry.id else # things didn't go so well, do something else end end
In this case, after saving our new entry to the database, the user is redirected to the show method which is then executed.
Calling multiple redirects or renders
An action should conclude with a single render or redirect. Attempting to try to do either again will result in a DoubleRenderError:
def do_something redirect_to :action => "elsewhere" render :action => "overthere" # raises DoubleRenderError end
If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
def do_something redirect_to(:action => "elsewhere") and return if monkeys.nil? render :action => "overthere" # won't be called unless monkeys is nil end
Constants
DEFAULT_RENDER_STATUS_CODE = "200 OK"
DEPRECATED_INSTANCE_VARIABLES = %w(cookies flash headers params request response session)
Attributes
[RW] | assigns | Holds the hash of variables that are passed on to the template class to be made available to the view. This hash is generated by taking a snapshot of all the instance variables in the current scope just before a template is rendered. |
[RW] | action_name | Returns the name of the action this controller is processing. |
Keep your controllers clear
When you use redirect_to or render with flash[:notice] or flash[:error], you can define some helper methods in your ApplicationController (or somewhere you want):
class ApplicationController < ActionController::Base protected %w(notice error).each do |message| class_eval <<-END_EVAL def redirect_#{message}(url, message) flash[:#{message}] = message redirect_to url end def render_#{message}(action, message) flash[:#{message}] = message render :action => action end END_EVAL end end
Now you have four methods - redirect_notice, redirect_error, render_notice and render_error.
Parsing YAML from a POST request
When building a REST server which should accept YAML there are several things to take into consideration.
First of the client should tell the server what type of data it is going to send. This is done via the Content-Type header (which is NOT only a response header as opposed to what the RESTful Web Services book from O’Reilly made us believe).
Second the server application should know how handle the body of the POST request. Placing the following line in your environment.rb:
ActionController::Base.param_parsers[Mime::YAML] = :yaml
This registers the YAML parser. Smooth sailing from here on!
Make sure your action names don't step on any toes.
In my experience, if you ever have a controller action named “process”, your controller will cease to function, as there is both a class and instance method called process in ActionController::Base.
There are undoubtedly other action names that will cause conflicts, but this one is particular I’ve run into a number of times.
session expiration
If you need to set expiration period for sessions through all controllers in your application, simply add the following option to your config/intializers/session_store.rb file:
:expire_after => 60.minutes
If you need to set different expiration time in different controllers or actions, use the following code in action or some before_filter:
request.session_options = request.session_options.dup request.session_options[:expire_after] = 5.minutes request.session_options.freeze
Duplication of the hash is needed only because it is already frozen at that point, even though modification of at least :expire_after is possible and works flawlessly.