Home arrow Ruby-on-Rails arrow Page 2 - Understanding Controllers in Ruby-on-Rails

Understanding Controllers in Ruby-on-Rails

In an MVC based web application, it is the controller that orchestrates and controls the flow of application logic. So to create an efficient, scalable and robust application, the clear understanding of the controller component provided by the framework is necessary. RoR is no exception.

Author Info:
By: APRajshekhar
Rating: 5 stars5 stars5 stars5 stars5 stars / 24
August 08, 2006
  1. · Understanding Controllers in Ruby-on-Rails
  2. · Routing the Requests, and Session Tracking
  3. · Filtering and Verification, and Caching
  4. · Rails in the Real World

print this article

Understanding Controllers in Ruby-on-Rails - Routing the Requests, and Session Tracking
(Page 2 of 4 )

1. Routing the requests

If you tried out the application developed in last part, you would remember a URL of the form of http://localhost:3001/admin/show/1/. The question that arises is, how does RoR map such a URL to a specific method or class? The mapping is done by routing the information contained in a file named routers.rb within the config directory. The information would look like the following code:

map.connect ':controller/service.wsdl', :action => 'wsdl'
map.connect ':controller/:action/:id'

The Routing component of the ActionController creates a map that connects the external URLs to the internals of the application. To make it more clear, look at the third line of the code block. The second map.connect statement contains the string ':controller/:action/:id'. It acts as a pattern to be matched against the path portion of the request URL. In the case of the request URL, the path can again be subdivided into three parts:

a. The first part would be assigned to the :controller part of the pattern.

b. The second part would be assigned to the :action part of the pattern.

c. The third part would be assigned to the :id part of the pattern.

On the basis of the above deduction, http://localhost:3001/demo/admin/1/ would be mapped as:

@params = { :controller => 'admin',
:action => 'show',
:id => 1 }

Based on this, RoR would invoke the show method in the admin controller with a parameter for the id of 1. Thus with this simple yet powerful technique, RoR does many things.

2. Session Tracking

Tracking a user across the application is the most required capability for any web application. Tracking can be done, in an efficient way, either by using cookies or session management provided by the framework. RoR provides both of these implicitly without the requirement of using explicit objects by means of the ActionController. Look at the following code block:

  class CookiesController < ApplicationController
    def create_cookie
      cookies[:the_time] = Time.now.to_s
      redirect_to :action =>

    def get_cookie
      cookie_value = cookies[:the_time]
      render(:text =>"The cookie says it is #{cookie_value}")

In the code above, there are two action methods in the Controller, one that sets a cookie and another that reads the cookie and displays the value. Here cookies[] is an implicit array/list of cookie objects. A new cookie can be added by specifying the name and providing the value.

Next the :action (which is a parameter of redirect_to) is given to the controller to which the request has to be redirected. In this case it is get_cookie action. In the second action the value of the cookie is extracted and shown using the render() method.

That covers cookies. But it is much better if there is a method to implement cookies transparently. That technique is the use of session. Just like cookies, session is also implicit. Its syntax and usage is similar to that of the cookie object. The following code will make it more clear:

  class SessionController < ApplicationController
    def login
       user = User.find_by_name_and_password(params[:user], params[:password])
      if user
        session[:user_id] = user.id
        redirect_to :action =>
      flash[:note] =
"Invalid user name/password"

The above code checks the user-id and password. If the user is valid it sets the user-id in session. The statement session[:user_id] = user.id. is the same as setting a cookie. Next the user is redirected to the index page. If the user is not valid, the session is invalidated using reset_session. This again reflects the simplicity of RoR.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials