Reputation: 6851
I have a quick question in regards to the collection_select helper in Rails 3.
I would like to create a drop down field whereby a user can select a country from a list.
My code currently looks something like this:
<%= collection_select(:country,:id,SyncedCountry.order('name ASC'),:name,:name,{},{:class => "input-xlarge"}) %>
When I submit on the page I see something like this in the params for country:
"country"=>{"id"=>"Antilles"}
What I really want is the id of the country selected in the drop-down and not in a hash format. So the result would be more like:
"country"=> 1 (the id of a country selected)
Any ideas?
Upvotes: 0
Views: 195
Reputation: 37409
From the documentation:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) public
...The
:value_method
and:text_method
parameters are methods to be called on each member of collection. The return values are used as the value attribute and contents of each<option>
tag, respectively. They can also be any object that responds to call, such as a proc, that will be called for each member of the collection to retrieve the value/text.
So try:
<%= collection_select(:country,:id,SyncedCountry.order('name ASC'),:id,:name,{},{:class => "input-xlarge"}) %>
The example in the documentation looks like this:
Sample usage (selecting the associated
Author
for an instance ofPost
,@post
):collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
If
@post.author_id
is already1
, this would return:<select name="post[author_id]"> <option value="">Please select</option> <option value="1" selected="selected">D. Heinemeier Hansson</option> <option value="2">D. Thomas</option> <option value="3">M. Clark</option> </select>
(this will return "author_id"=>"1")
Now, I'm not familiar with your model, but if you are selecting the country of your user, than I think this should work:
<%= collection_select(:user, :country_id,SyncedCountry.order('name ASC'),:id,:name,{},{:class => "input-xlarge"}) %>
Upvotes: 0
Reputation: 53038
Replace
<%= collection_select(:country,:id,SyncedCountry.order('name ASC'),:name,:name,{},{:class => "input-xlarge"}) %>
with
<%= collection_select(:model_object,:country,SyncedCountry.order('name ASC'),:name,:name,{},{:class => "input-xlarge"}) %>
where model_object
is the object passed to form. If its a form for user
and your form looks like form_for(@user)
then replace :model_object
with :user
.
So, params would look like "user"=>{"country"=>"Antilles"}
, assuming that you are setting country for a user.
Upvotes: 1