Dynamically Generate a Selection List in a Rails Template - Rendering the HTTP Response
(Page 3 of 4 )
How is that response rendered, anyway? Let’s look at that part of the controller object:
class HacksController < ApplicationController
def index
end
def create_select
indArr=["Nordic Skiing", "Inline Skating","Tennis",
"Triathlon","Road Racing","Figure Skating","Weight Lifting",
"Speed Skating","Snowboarding"];
teamArr=["Soccer","Basketball","Football","Hockey",
"Baseball","Lacrosse"];
str="";
if params[:categories].index('Team') != nil
render :partial => "options",
:locals => { :sports => teamArr,:sptype => "team"}
elsif params[:categories].index('Individual') != nil
render :partial => "options",
:locals => { :sports => indArr, :sptype => "individual" }
else
str="<select id='individual' name='individual'>
option>unknown</option></select>";
render :text => str;
end
#end method
end
#end class definition
end
This controller object stores two Rubyarrays in the variablesindArrandteamArr (these values could alternatively be generated from a database). Remember the web page’s existingselectlist that gives the user a choice of Team or Individual? This is aselectelement with thename categories. The browser submits this value as a form parameter to the Rails action. The code uses the syntaxparams[:categories] to get this parameter’s value. Then things get interesting, in a Rails kind of way. The server still has to provide an HTTP response to the Ajax request object.
The action uses the RoRrender()method to send the HTML for aselectlist back to our application, with thearrayvalues as theselect list contents:
render :partial => "options",
:locals => { :sports => teamArr,:sptype => "team"}
render()specifies in its first parameter apartialnamedoptions. In Rails lingo, apartialis just a template that contains a chunk of content that can be used over and over again—for example, one or a few HTML tags. Using the Rails naming convention, thepartial(really a text file) is placed in the app/ views/hacks directory with its name preceded by an underscore, as in _options. rhtml. So, in plain English, the method call declares, “Render the response as
the_options partialcontent, and hand thepartialtwo local variables,:sportsand:sptype.”
Don’t forget the : before the variable names!
Next: A Little Partial Pizzazz >>
More JavaScript Articles
More By O'Reilly Media
|
This article is excerpted from hack 58 of the book Ajax Hacks, written by Bruce W. Perry (O'Reilly; ISBN: 0596101694). Check it out today at your favorite bookstore. Buy this book now.
|
|