Oomoo

March 11, 2008

Controllers Broken Down

Filed under: classes, controller, rails — oomoo @ 1:13 pm

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.

After executing the code in the method, Controller methods (actions), by default, render a page in the app/views directory corresponding to the name of the controller and 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. 

A sample controller could look like this:  
 

    class OrdersController < ApplicationController
      def index
        @order = Order.find :first
      end
     
      def new
        @order = Order.new 
        @order.ordPK = 3
        @order.ordCustPONum =
      end
    end 
     

Session and Request

Just like when using West Wind Web Connection…

The “Session” object and “Request” object (which are created as part of any HTTP “Get” or “Post”) are passed to the Controller. 

This is how the Controller is able to know the “action” (method) that is to be performed.  It extracts it out of the Request object. 
 

Params[]

A “hash” containing the parameters from the “Request” object (or from the URL).

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=”1 main street”> 

A request stemming from a form holding these inputs will include

{ “post” => { “name” => “david”, “address” => “1 main street” } }.  
 

Session

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]} 
 

Response

Each action results in a response object, 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.  

An “action” may perform a single “Render” or “Redirect”  
 

Render

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 
 

Redirect

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

To Create A Controller 

(from Ruby cmd prompt)  ruby script/generate controller myname index 

Creates:

  app/contollers/myname_controller.rb

  app/helpers/myname_controller.rb

  app/views/myname/index.rhtml

  test/functional/myname_controller_test.rb 

To Verify:

   (from Ruby command prompt)  ruby script/server

   (browse to) http://localhost:3000/myname 
 
 

See Also: http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/
See Also: http://api.rubyonrails.org/classes/ActionController/Base.html 

*Much of this post was transcribed from a Rails screencast.  I am looking for the source to give credit.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: