Dynamically Generate a Selection List in a Rails Template - A Little Partial Pizzazz (Page 4 of 4 )
Thepartialneeds thearrayvalues to build theselectlist; these are stored in theteamArrvariable. Rails uses its built-in naming convention forpartials (the underscore requirement) to find the correct content and render it as the response. Let’s look at thepartial_options.rhtml file:
<select id="<%= sptype %>" name="<%= sptype %>"> <% sports.each do |sport| %> <option><%= sport %></option> <% end %> </select>
A little embedded Ruby code gives theselectelement itsidandname. The embedded code then iterates through thearray(passed into thepartialby therender()method) and creates anoptionelement for eacharraymember, as in<option>hockey</option>. Although a little server-side Ruby code was involved, the code did not have to touch the request object or deal with fetching or massaging the return value.
Cleanup Code
The only bit of trickery involved is making sure that the application does not append one newselect list after another inside thedivas the user clicks the button. We want all the existingselects in thatdivto be replaced by any new ones. Therefore, we include a little cleanup code that empties thedivbefore it’s updated with a newselect list:
successsequentially precedes thecompletestage, so this code sets thediv’s content to the emptystring before the newselect list appears.
To handle any request failures, such as a downed web server, add this code from a prior hack as aform_remote_tag()parameter:
#$('failure') is Prototype's shortcut for #document.getElementById('failure') :failure => "$('failure').innerHTML='Failure; request status='+request.status"
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.