cat
cat

Reputation: 749

Why the option 'selected' is not working in this?

When I access to the url like example.com/shop?genre=13,
It should automatically show the default selection set with the value 13. However, it shows very first line of selection.
Why?

 <%= select_tag :genre, options_for_select(Genre.all.map{ |g| [g.name, g.id] }),  :selected => params[:genre] %>

Upvotes: 0

Views: 63

Answers (2)

Yves Senn
Yves Senn

Reputation: 1996

If you want to select an option, you need to pass the value to the options_for_select method. If you lookup the signature for the method you will find:

options_for_select(container, selected = nil)

Further reading of the docs at http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select will lead you to the example:

options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum")
  <option value="Free" selected="selected">Free<%roption>\n<option value="Basic">Basic</ption>\n<option value="Advanced">Advanced<%roption>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>

In your case you should be able to get it working with:

<%= select_tag :genre, options_for_select(Genre.all.map{ |g| [g.name, g.id] },  :selected => params[:genre]) %>

As a side note. I guess Genre is an ActiveRecord model. In this case you can use options_from_collection_for_select. This method is designed to create a list of options tags from an array of ActiveRecord models. You find the docs at: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_from_collection_for_select

Your code could look something like:

<%= select_tag :genre, options_from_collection_for_select(Genre.all, 'id', 'name', params[:genre]) %>

Upvotes: 1

RadBrad
RadBrad

Reputation: 7304

<%= select_tag :genre, options_for_select(Genre.all.map{ |g| [g.name, g.id] },params[:genre]) %>

options_for_select take two arguments, the Array with select options, and then the value you want shown selected.

You had ONE argument to options_for_select

Upvotes: 1

Related Questions