Action Pack - Ruby On rails from request to response

By: David Heinemeier Hansson Emailed: 1644 times Printed: 2120 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Action Pack splits the response to a web request into a controller part (performing the logic) and a view part (rendering a template). This two-step approach is known as an action, which will normally create, read, update, or delete (CRUD for short) some sort of model part (often backed by a database) before choosing either to render a template or redirecting to another action.

Action Pack implements these actions as public methods on Action Controllers and uses Action Views to implement the template rendering. Action Controllers are then responsible for handling all the actions relating to a certain part of an application. This grouping usually consists of actions for lists and for CRUDs revolving around a single (or a few) model objects. So ContactController would be responsible for listing contacts, creating, deleting, and updating contacts. A WeblogController could be responsible for both posts and comments.

Action View templates are written using embedded Ruby in tags mingled in with the HTML. To avoid cluttering the templates with code, a bunch of helper classes provide common behavior for forms, dates, and strings. And it‘s easy to add specific helpers to keep the separation as the application evolves.

Note: Some of the features, such as scaffolding and form building, are tied to ActiveRecord (an object-relational mapping package), but that doesn‘t mean that Action Pack depends on Active Record. Action Pack is an independent package that can be used with any sort of backend (Instiki, which is based on an older version of Action Pack, used Madeleine for example). Read more about the role Action Pack can play when used together with Active Record on

A short rundown of the major features:

  • Actions grouped in controller as methods instead of separate command objects and can therefore share helper methods
      BlogController < ActionController::Base
        def show
          @customer = find_customer
        def update
          @customer = find_customer
          @customer.attributes = params[:customer]
            redirect_to(:action => "display") :
            render(:action => "edit")
          def find_customer() Customer.find(params[:id]) end
  • Embedded Ruby for templates (no new "easy" template language)
      <% for post in @posts %>
        Title: <%= post.title %>
      <% end %>
      All post titles: <%= @post.collect{ |p| p.title }.join ", " %>
      <% unless @person.is_client? %>
        Not for clients to see...
      <% end %>
  • Builder-based templates (great for XML content, like RSS)
      xml.rss("version" => "2.0") do do

          xml.description "Basecamp: Recent items"
          xml.language "en-us"
          xml.ttl "40"
          for item in @recent_items
            xml.item do
  • Filters for pre and post processing of the response (as methods, procs, and classes)
      class WeblogController < ActionController::Base
        before_filter :authenticate, :cache, :audit
        after_filter { |c| c.response.body = Gzip::compress(c.response.body) }
        after_filter LocalizeFilter
        def index
          # Before this action is run, the user will be authenticated, the cache
          # will be examined to see if a valid copy of the results already
          # exists, and the action will be logged for auditing.
          # After this action has run, the output will first be localized then
          # compressed to minimize bandwidth usage
          def authenticate
            # Implement the filter with full access to both request and response
  • Helpers for forms, dates, action links, and text
      <%= text_field "post", "title", "size" => 30 %>
      <%= html_date_select( %>
      <%= link_to "New post", :controller => "post", :action => "new" %>
      <%= truncate(post.title, 25) %>
  • Layout sharing for template reuse (think simple version of Struts Tiles)
      class WeblogController < ActionController::Base
        layout "weblog_layout"
        def hello_world
      Layout file (called weblog_layout):
        <html><body><%= yield %></body></html>
      Template for hello_world action:
        <h1>Hello world</h1>
      Result of running hello_world action:
        <html><body><h1>Hello world</h1></body></html>
  • Routing makes pretty urls incredibly easy
      map.connect 'clients/:client_name/:project_name/:controller/:action'
      Accessing /clients/37signals/basecamp/project/dash calls ProjectController#dash with
      { "client_name" => "37signals", "project_name" => "basecamp" } in params[:params]
      From that URL, you can rewrite the redirect in a number of ways:
      redirect_to(:action => "edit") =>
      redirect_to(:client_name => "nextangle", :project_name => "rails") =>
  • Javascript and Ajax integration
      link_to_function "Greeting", "alert('Hello world!')"
      link_to_remote "Delete this post", :update => "posts",
                     :url => { :action => "destroy", :id => }
  • Pagination for navigating lists of results
      # controller
      def list
        @pages, @people =
          paginate :people, :order => 'last_name, first_name'
      # view
      <%= link_to "Previous page", { :page => @pages.current.previous } if @pages.current.previous %>
      <%= link_to "Next page", { :page => } if %>
  • Easy testing of both controller and rendered template through ActionController::TestCase
      class LoginControllerTest < ActionController::TestCase
        def test_failing_authenticate
          process :authenticate, :user_name => "nop", :password => ""
          assert flash.has_key?(:alert)
          assert_redirected_to :action => "index"
  • Automated benchmarking and integrated logging
      Processing WeblogController#index (for at Fri May 28 00:41:55)
      Parameters: {"action"=>"index", "controller"=>"weblog"}
      Rendering weblog/index (200 OK)
      Completed in 0.029281 (34 reqs/sec)
      If Active Record is used as the model, you'll have the database debugging
      as well:
      Processing WeblogController#create (for at Sat Jun 19 14:04:23)
      Params: {"controller"=>"weblog", "action"=>"create",
               "post"=>{"title"=>"this is good"} }
      SQL (0.000627) INSERT INTO posts (title) VALUES('this is good')
      Redirected to http://test/weblog/display/5
      Completed in 0.221764 (4 reqs/sec) | DB: 0.059920 (27%)
      You specify a logger through a class method, such as:
      ActionController::Base.logger ="Application Log")
      ActionController::Base.logger ="Application Log")
  • Caching at three levels of granularity (page, action, fragment)
      class WeblogController < ActionController::Base
        caches_page :show
        caches_action :account
        def show
          # the output of the method will be cached as
          # ActionController::Base.page_cache_directory + "/weblog/show/n.html"
          # and the web server will pick it up without even hitting Rails
        def account
          # the output of the method will be cached in the fragment store
          # but Rails is hit to retrieve it, so filters are run
        def update
          List.update(params[:list][:id], params[:list])
          expire_page   :action => "show", :id => params[:list][:id]
          expire_action :action => "account"
          redirect_to   :action => "show", :id => params[:list][:id]
  • Component requests from one controller to another
      class WeblogController < ActionController::Base
        # Performs a method and then lets hello_world output its render
        def delegate_action
          render_component :controller => "greeter",  :action => "hello_world"
      class GreeterController < ActionController::Base
        def hello_world
          render_text "Hello World!"
      The same can be done in a view to do a partial rendering:
        Let's see a greeting:
        <%= render_component :controller => "greeter", :action => "hello_world" %>
  • Powerful debugging mechanism for local requests
      All exceptions raised on actions performed on the request of a local user
      will be presented with a tailored debugging screen that includes exception
      message, stack trace, request parameters, session contents, and the
      half-finished response.
  • Scaffolding for Active Record model objects
      class AccountController < ActionController::Base
        scaffold :account
      The AccountController now has the full CRUD range of actions and default
      templates: list, show, destroy, new, create, edit, update
  • Form building for Active Record model objects
      The post object has a title (varchar), content (text), and
      written_on (date)
      <%= form "post" %>
      ...will generate something like (the selects will have more options, of
      <form action="create" method="POST">
          <input type="text" name="post[title]" value="<%= @post.title %>" />
          <textarea name="post[content]"><%= @post.title %></textarea>
          <b>Written on:</b><br/>
          <select name='post[written_on(3i)]'><option>18</option></select>
          <select name='post[written_on(2i)]'><option value='7'>July</option></select>
          <select name='post[written_on(1i)]'><option>2004</option></select>
        <input type="submit" value="Create">
      This form generates a params[:post] array that can be used directly in a save action:
      class WeblogController < ActionController::Base
        def create
          post = Post.create(params[:post])
          redirect_to :action => "display", :id =>
  • Runs on top of WEBrick, Mongrel, CGI, FCGI, and mod_ruby

Ruby Home | All Ruby Tutorials | Latest Ruby Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


Be the first one to add a comment

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by David Heinemeier Hansson
Sending emails and Receiving emails using Ruby On rails
Action Pack - Ruby On rails from request to response
Defining tables and classes (using MySQL) in Ruby on Rails
Active Record in Ruby on Rails

More Tutorials in Ruby
Standard Library Packages in Ruby
Module Abbrev in Ruby
encoding and decoding in Ruby using Base64 Module
Benchmark module in Ruby
benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) {|report| ...} in Ruby
bm(label_width = 0, *labels) {|report| ...} in Ruby
bmbm(width = 0) {|job| ...} in Ruby
CGI class in Ruby
URL encode a string in Ruby
escapeElement() in Ruby
escapeHTML() in Ruby
new(type = "query") in Ruby
parse(query) in Ruby
pretty() in Ruby
Format a Time object as a String in Ruby

More Latest News
Most Viewed Articles (in Ruby )
if . . . elsif . . . else in Ruby on rails
unless in Ruby on rails
URL encode a string in Ruby
Reading URL content using Ruby (HTTP)
Using Proxy to connect to URLs in Ruby
Reading emails using POP3 in Ruby
Prompts, Command Lines, Prompts, and irb in Ruby on rails
The Question Mark Operator in Ruby on rails
encoding and decoding in Ruby using Base64 Module
bmbm(width = 0) {|job| ...} in Ruby
escapeHTML() in Ruby
new(type = "query") in Ruby
unescapeElement() in Ruby
header() in Ruby
Open and manipulate CSV files in Ruby
Most Emailed Articles (in Ruby)
if . . . elsif . . . else in Ruby on rails
header() in Ruby
encoding and decoding in Ruby using Base64 Module
Using GServer in Ruby
Getting started with Ruby on rails
Standard Library Packages in Ruby
Module Abbrev in Ruby
bmbm(width = 0) {|job| ...} in Ruby
CGI class in Ruby
escapeElement() in Ruby
unescapeHTML() in Ruby
Open and manipulate CSV files in Ruby
Reading emails using POP3 in Ruby
Command-line Arguments in Ruby on rails
POST a form in Ruby