Home arrow Ruby-on-Rails arrow Action Pack Request Parameters
RUBY-ON-RAILS

Action Pack Request Parameters


In this eighth part of a series on the Action Pack library for Rails, you will learn how to handle request parameters and how to use the render method. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
April 21, 2011
TABLE OF CONTENTS:
  1. · Action Pack Request Parameters
  2. · Rendering Responses

print this article
SEARCH DEVARTICLES

Action Pack Request Parameters
(Page 1 of 2 )

Processing Request Parameters

Request parameters—whether they originate from requests of the GETorPOSTvariety—are accessible via theparamshash. To be specific,paramsis really a method that returns aHashobject so you can access it using hash semantics. Hashes in Ruby aresimilar to arrays, but indexed by arbitrary keys, unlike arrays whichare indexed (and ordered) by number. (If you need a quick review of theHashobject, flip to Appendix A for a Ruby primer.)

The value of any request variable can be retrieved by its symbolized key. So, if there’s a variable calledidin the request parameters, you can access it withparams[:id]. Likewise, both the controller and the action name are also request parameters, stored in theparamshash by the routing component when it picked apart the request. You can get their values by usingparams[:controller]andparams[:action].

Just to drive this concept home, let’s look at a sample URL and display theparamshash that it would populate.

http://localhost:3000/users/index?name=arthur&number=1037

params #=> { :controller => 'users',
            
:action     => 'index',
            
:name       => 'arthur',
             :number     => '1037' }

Writing a Create Action

With an understanding of paramsunder your belt, let’s continue developing our controller. Thecreate action is the target of the formsubmission. As you saw in the error message you just triggered, you’llneed to write this action if you expect anything worthwhile to happen.Let’s do that now. Add the method shown in Listing 6-5 to youruserscontroller, just under thenewmethod:

Listing 6-5. Create Action Added to app/controllers/users_controller.rb

def create
 
@user = User.new(params[:user])
 
if @user.save
   
flash[:notice] = 'Thanks for signing up!'
   
redirect_to :controller => 'events', :action => 'index' 
  else
    render :action => 'new'
  end
end

Let’s walk through this. First, we initialize a newUser object with whatever attributes come in via theparams hash, storing it the@userinstance variable. Then we try to save it.

If the save is successful, we use a facility that Rails provides called theflashto set a message before redirecting to theindexaction on theevents controller. Theflashis a special kind of storage mechanismprovided by Rails for convenience. It encapsulates the pattern ofwanting to set a message on one action and have that message persist tothe next, only to disappear after that action is rendered. This isuseful for providing user feedback, as we’re doing here to say “Thanksfor signing up.” If you look back to your layout file inapp/views/layouts/application.rhtml, you’ll see where theflashmessage is displayed:

<p style="color: green"><%= flash[:notice] %></p>

Theflashmessage we set will be available to the controller and action we redirect to (theindexaction on theeventscontroller). Just likeparams, theflashisimplemented as a Ruby hash. You store values in it based on a key. Thekey can be anything you like, but here we’re using the symbol:notice, which is a Rails convention. When rendering aflashmessage that contains an error, we usually use the:errorkey.

If the save fails, we render thenewaction again so that any errors can be corrected.


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-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials