Flowdock

Action <a href="/rails/Controllers">Controllers</a> are made up of one or more actions that performs its purpose and then either renders a template or redirects 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 a mod_rewrite mapping. 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

  GuestBookController.template_root = "templates/"
  GuestBookController.process_cgi

All actions assume that you want to render a template matching the name of the action at the end of the performance unless you tell it otherwise. The index action complies with this assumption, so after populating the @entries instance variable, the GuestBookController will render "templates/guestbook/index.rhtml".

Unlike index, the sign action isn’t interested in rendering a template. So after performing its main purpose (creating a new entry in the guest book), it sheds the rendering assumption and 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 <a href="/rails/Controllers">Controllers</a>. Get-and-show and do-and-redirect. Most actions are variations of these themes.

Also note that it’s the final call to process_cgi that actually initiates the action performance. It will extract request and response objects from the CGI

When Action Pack is used inside of Rails, the template_root is automatically configured and you don’t need to call process_cgi yourself.

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 hello_ip
    location = request.env["REMOTE_IP"]
    render :text => "Hello stranger from #{location}"
  end

Parameters

All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params hash. So 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 memory 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 hash accessor:

  session[:person] = Person.authenticate(user_name, password)

And retrieved again through the same hash:

  Hello #{session[:person]}

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 memory overhead. In other words, think carefully about size and caching before resorting to the use of the session.

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.

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, so it’s normally nothing you’ll need to be concerned about.

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

Redirecting is what actions that update the model do when they’re done. The save_post method shouldn’t be responsible for also showing the post once it’s saved — that’s the job for show_post. So once save_post has completed its business, it’ll redirect to show_post. All redirects are external, which means that when the user refreshes his browser, it’s not going to save the post again, but rather just show it one more time.

This sounds fairly simple, but the redirection is complicated by the quest for a phenomenon known as "pretty urls". Instead of accepting the dreadful being that is "weblog_controller?action=show&post_id=5", Action Controller goes out of its way to represent the former as "/weblog/show/5". And this is even the simple case. As an example of a more advanced pretty url consider "/library/books/ISBN/0743536703/show", which can be mapped to books_controller?action=show&type=ISBN&id=0743536703.

Redirects work by rewriting the URL of the current action. So if the show action was called by "/library/books/ISBN/0743536703/show", we can redirect to an edit action simply by doing redirect_to(:action => "edit"), which could throw the user to "/library/books/ISBN/0743536703/edit". Naturally, you’ll need to setup the routes configuration file to point to the proper controller and action in the first place, but once you have, it can be rewritten with ease.

Let’s consider a bunch of examples on how to go from "/clients/37signals/basecamp/project/dash" to somewhere else:

  redirect_to(:action => "edit") =>
    /clients/37signals/basecamp/project/dash

  redirect_to(:client_name => "nextangle", :project_name => "rails") =>
    /clients/nextangle/rails/project/dash

Those redirects happen under the configuration of:

  map.connect 'clients/:client_name/:project_name/:controller/:action'

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

Environments

Action Controller works out of the box with CGI, FastCGI, and mod_ruby. CGI and mod_ruby controllers are triggered just the same using:

  WeblogController.process_cgi

FastCGI controllers are triggered using:

  FCGI.each_cgi{ |cgi| WeblogController.process_cgi(cgi) }

Aliases

  • process

Constants

DEFAULT_RENDER_STATUS_CODE = "200 OK"

Attributes

[RW] params

Holds a hash of all the GET, POST, and Url parameters passed to the action. Accessed like params["post_id"] to get the post_id. No type casts are made, so all values are returned as strings.

[RW] request

Holds the request object that’s primarily used to get environment variables through access like request.env["REQUEST_URI"].

[RW] response

Holds the response object that’s primarily used to set additional HTTP headers through access like response.headers["Cache-Control"] = "no-cache". Can also be used to access the final body HTML after a template has been rendered through response.body — useful for after_filters that wants to manipulate the output, such as a OutputCompressionFilter.

[RW] session

Holds a hash of objects in the session. Accessed like session[:person] to get the object tied to the "person" key. The session will hold any type of object as values, but the key should be a string or symbol.

[RW] headers

Holds a hash of header names and values. Accessed like headers["Cache-Control"] to get the value of the Cache-Control directive. Values should always be specified as strings.

[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.

Show files where this class is defined (4 files)
Register or log in to add new notes.
July 23, 2008
4 thanks

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.

November 7, 2008
2 thanks

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!

June 1, 2009
2 thanks

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.

September 1, 2009 - (>= v2.3.2)
1 thank

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.

from - http://squarewheel.pl/posts/3