Ruby on Rails: defaults helpers onchange options_for_select Rails select select_tag to_sym
by bseanvt
2 comments
Rails Select Tag and Onchange Event Calling a Remote Function with Default Option Selected
Here is a little code snippet that will fire off a request to update_client_path when you change the select field. This stands alone, rather than being apart of a larger form. The Client::CATEGORY argument is a hash, which I populated manually in my Client.rb model. It is something like this
CATEGORY = {:lead => "Prospective clients", :past => "Previous clients..."}
In my view I have
<%= select_tag "client_category",
options_for_select(Client::CATEGORY.keys, @client.category.to_sym),
{ :onchange => remote_function( :url => update_client_path(@client), :with=>"'change_to='+this.value+''" ) } %>
One gotcha is that the select_tag, options_for_select argument expects a symbol if you’re passing in a hash as the type of the collection! It may not set the default if you provide it with a string for the second arg (which specifies which option should be set as selected).
You also need to make sure that the url update_client_path is set in your routes file and that your controller (clients_controller in this case) has the appropriate method to handle the request.
Posts Ruby on Rails: api collection helpers html select
by bseanvt
leave a comment
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...
<pre id="line27"><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>
</select>


