Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 2 - Rails Action Controller
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Rails Action Controller
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-01-24

    Table of Contents:
  • Rails Action Controller
  • 4.1 Accessing Form Data from a Controller
  • 4.2 Changing an Application’s Default Page
  • 4.3 Clarifying Your Code with Named Routes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Rails Action Controller - 4.1 Accessing Form Data from a Controller


    (Page 2 of 4 )

    Problem

    You have a web form that collects data from the user and passes it to a controller. You want to access that data within the controller.

    Solution

    Use the params hash. Given the form:

    app/views/data/enter.rhtml:

      <h2>Form Data - enter</h2>

      <% form_tag(:action => "show_data") do %>

       <p>Name:
       <%= text_field_tag("name","Web Programmer") %></p>

       <p>Tools:  
       <% opts = ["Perl", "Python",
    "Ruby"].map do |o| 
       "<option>#{o}</option>"
      end.to_s    %>
       <%= select_tag("tools[]", opts, :multiple => "true") %></p>

       <p>Platforms:
       <%= check_box_tag("platforms[]","Linux") %> Linux
       <%= check_box_tag("platforms[]","Mac OSX") %> Mac OSX
      <%= check_box_tag("platforms[]","Windows") %> Windows</p>

       <%= submit_tag("Save Data") %>
      <% end %>

    When the form has been submitted, you can access the data using the params hash within your controller.

    app/controllers/data_controller.rb:

     class DataController < ApplicationController

      def enter
      end

      def show_data
       @name = params[:name]
       @tools = params[:tools] || [] 
       @platforms = params[:platforms] || []
       end
      end


    Figure 4-1.  A web form containing several HTML input elements

    Discussion

    The web server stores the elements of a submitted form in the request object. These elements are available to your application through the params hash. The params hash is unique because you can access its elements using strings or symbols as keys.

    Figure 4-1 shows the form; it has three different types of HTML elements.

    The following view displays the data that the form collects. The last line is a call to the debug template helper, which displays the contents of the params hash in yaml format:

    app/views/data/show_data.rhtml:

      <h2>Form Data - display</h2>

      Name: <%= @name %>;
      Tools: <%= @tools.join(", ") %>; 
      Platforms: <%= @platforms.join(", ") %>; 

      <hr>
      <%= debug(params) %>

    Figure 4-2 shows the rendered view.

      


    Figure 4-2.  Form data displayed in a view with additional debugging output

    To access the name field of the form, use :name as the key to the params hash (e.g., params [:name]). The selected elements of the multiselect list and the checkboxes are stored in the params hash as arrays named after their associated HTML element names.

    For example, if you submit the form in the solution with Python and Ruby selected for Tools and Mac OS X checked for Platforms, the params hash contains the following arrays:

      { "tools"=>["Python", "Ruby"], "platforms"=>["Mac OSX"] }

    This behavior is triggered by appending [] to the name of an element that can have more than one value. If no items are selected, there will be no variable in params corresponding to that element.

    Form data can also be structured as an arbitrarily deeply nested tree of hashes and arrays within the params hash. Hashes are created by placing the name of the nested hash between the square brackets at the end of the field name. The following hidden form fields illustrate a nesting that is up to three levels deep (i.e., params contains a student hash, which contains a scores hash, which contains a :midterm array with values and :final key with a value).

      <input type="hidden" name="student[scores][midterm][]" value="88">
      <input type="hidden" name="student[scores][midterm][]" value="91">
      <input type="hidden" name="student[scores][final]" value="95">

    If you add these hidden fields to the solution’s form, you get the following student data structure params hash:

      "student"=> {
       
    "scores"=> {
         "final"=>"95",
        "midterm"=> [
          "88",
         "91"
        ]
       }
      }

    Here’s how to access the student’s second midterm scores:

      params[:student][:scores][:midterm][1]

    See Also

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · This article is an excerpt from the "Rails Cookbook," published by O'Reilly. We hope...
       · Thanks for the nice article.On page 3 of 4, the second paragraph in the...
     

    Buy this book now. This article is excerpted from chapter four of the Rails Cookbook. written by Rob Orsini (O'Reilly, 2007; ISBN: 0596527314). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops
    - Ruby Conditionals
    - Ruby Operators and Arrays
    - Ruby for the Newbie







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway