Home arrow Ruby-on-Rails arrow Page 2 - Rails Action Controller
RUBY-ON-RAILS

Rails Action Controller


The Rails Action Controller does what you would expect from the name: it receives a request and then decides what action will handle it. This article, the first of a four-part series, introduces you to the Action Controller. It is excerpted from chapter four of the Rails Cookbook, written by Rob Orsini (O'Reilly, 2007; ISBN: 0596527314). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 10
January 24, 2008
TABLE OF CONTENTS:
  1. · Rails Action Controller
  2. · 4.1 Accessing Form Data from a Controller
  3. · 4.2 Changing an Application’s Default Page
  4. · 4.3 Clarifying Your Code with Named Routes

print this article
SEARCH DEVARTICLES

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


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- 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 
Support 

Developer Shed Affiliates

 




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