Class

Base

Extends:

Includes:

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.erb 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 name="post[name]" type="text" value="david" />
<input name="post[address]" type="text" 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.

Sessions are stored in a browser cookie that’s cryptographically signed, but unencrypted, by default. This prevents the user from tampering with the session but also allows him to see its contents.

Do not put secret information in session!

Other options for session storage are:

ActiveRecordStore: sessions are stored in your database, which works better than PStore with multiple app servers and, unlike CookieStore, hides your session contents from the user. To use ActiveRecordStore, set

config.action_controller.session_store = :active_record_store

in your environment.rb and run rake db:sessions:create.

MemCacheStore: sessions are stored as entries in your memcached cache. Set the session store type in environment.rb:

 config.action_controller.session_store = :mem_cache_store

This assumes that memcached has been installed and configured properly.  See the MemCacheStore docs for more information.

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 link:classes/ActionView/Base.html.

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 may contain only a single render or a single 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
Public Attributes
action_name Returns the name of the action this controller is processing.
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.
Public Methods
append_view_path Adds a view_path to the end of the view_paths array. If the current class has no view paths, copy them from the superclass. This change will be visible for all future requests.
append_view_path Adds a view_path to the end of the view_paths array. This change affects the current request only.
controller_class_name Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
controller_class_name Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
controller_name Converts the class name from something like "OneModule::TwoModule::NeatController" to "neat".
controller_name Converts the class name from something like "OneModule::TwoModule::NeatController" to "neat".
controller_path Converts the class name from something like "OneModule::TwoModule::NeatController" to "one_module/two_module/neat".
controller_path Converts the class name from something like "OneModule::TwoModule::NeatController" to "one_module/two_module/neat".
exempt_from_layout Don’t render layouts for templates with the given extensions.
filter_parameter_logging Replace sensitive parameter data from the request log. Filters parameters that have any of the arguments as a substring. Looks in all subhashes of the param hash for keys to filter. If a block is given, each key and value of the parameter hash and all subhashes is passed to it, the value or key can be replaced using String#replace or similar method.
hidden_actions Return an array containing the names of public methods that have been marked hidden from the action processor. By default, all methods defined in ActionController::Base and included modules are hidden. More methods can be hidden using hide_actions.
hide_action Hide each of the given methods from being callable as actions.
prepend_view_path Adds a view_path to the front of the view_paths array. This change affects the current request only.
prepend_view_path Adds a view_path to the front of the view_paths array. If the current class has no view paths, copy them from the superclass. This change will be visible for all future requests.
process Factory for the standard create, process loop where the controller is discarded after processing.
process Extracts the action_name from the request parameters and performs that action.
process_cgi Process a request extracted from a CGI object and return a response. Pass false as session_options to disable sessions (large performance increase if sessions are not needed). The session_options are the same as for CGI::Session:
process_cgi
process_test
process_test Process a test request called with a TestRequest object.
process_with_test
session_enabled?
url_for Returns a URL that has been rewritten according to the options hash and the defined Routes. (For doing a complete redirect, use redirect_to).   url_for is used to:   All keys given to url_for are forwarded to the Route module, save for the following:
view_paths View load paths determine the bases from which template references can be made. So a call to render("test/template") will be looked up in the view load paths array and the closest match will be returned.
view_paths View load paths for controller.
view_paths=
view_paths=
Protected Methods
default_url_options Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in the form of a hash, just like the one you would use for url_for directly. Example:
erase_redirect_results Clears the redirected results from the headers, resets the status to 200 and returns the URL that was used to redirect or nil if there was no redirected URL Note that redirect_to will change the body of the response to indicate a redirection. The response body is not reset here, see erase_render_results
erase_render_results Clears the rendered results, allowing for another render to be performed.
erase_results Erase both render and redirect results
expires_in Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a "private" instruction, so that intermediate caches shouldn’t cache the response.
expires_now Sets a HTTP 1.1 Cache-Control header of "no-cache" so no caching should occur by the browser or intermediate caches (like caching proxy servers).
head Return a response that has no content (merely headers). The options argument is interpreted to be a hash of header names and values. This allows you to easily return a response that consists only of significant headers:
redirect_to Redirects the browser to the target specified in options. This parameter can take one of three forms:
render Renders the content that will be returned to the browser as the response body.
render_to_string Renders according to the same rules as render, but returns the result in a string instead of sending it as the response body to the browser.
reset_session Resets the session by clearing out all the objects stored within and initializing a new session object.
rewrite_options
Private Methods
action_methods
action_methods
add_class_variables_to_assigns
add_instance_variables_to_assigns
add_variables_to_assigns
assert_existence_of_template_file
assign_default_content_type_and_charset
assign_names
assign_shortcuts
close_session
complete_request_uri
default_render
default_template_name
forget_variables_added_to_assigns
initialize_current_url
initialize_template_class
log_processing
perform_action
performed?
process_cleanup
protected_instance_variables
render_for_file
render_for_text
request_origin
reset_variables_added_to_assigns
sending_file?
strip_out_controller
template_exempt_from_layout?
template_exists?
template_path_includes_controller?
template_public?
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.