now available

now available
Want fresh tech tips in your inbox?

Collection Select Helper and OnChange Event in Rails


Given a collection of Active Record objects, you may use the collection_select helper method to produce a select form field. You need to pass in a number of arguments to the helper function.

1) object - your model object used in the collection 2) method - a valid model attribute or method 3) collection - a collection of active record model objects 4) option_value - value being set from the model for the <option value="option_value"> html element 5) option_name - what is displayed for the user e.g., <option> option_name < 6) option - general options 7) options for the select html element

# helper and arguments...

collection_select( model, id, collection, option_value, option_name, options, html_options)

<%= collection_select("states", "state_id", State.participating, "abbreviation", "name", {:selected=> get_current_state_or_nil }, {:onchange=>"document.location='/states/'+this.value"} ) %>

which will produce something like...

<select id="state_id" name="state[id]" onchange="document.location='/states/'+this.value">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>

Tagged w/ #api #collection #helpers #html #selectposts #ruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app