Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set "selected" in select_tag/options_from_collection_for_select

I've been searching stackoverflow for almost 2 hours now going through similar questions but the answers just don't seem to work.

I have the following code:

<%= select_tag "name_dropdown", options_from_collection_for_select(@models, "friendly_id", "name") %>

I'd like to display the option I've chosen previously as selected instead of going to the first tag by default.

In the other questions they've suggested to add the following (none of them work).

<%= select_tag "name_dropdown", options_from_collection_for_select(@models, "friendly_id", "name", "1") %>

Or:

<%= select_tag "name_dropdown", options_from_collection_for_select(@models, "friendly_id", "name", @models.first.id) %>

ps. I'm using Rails 3.1.RC4

like image 252
imjp Avatar asked Jul 16 '11 21:07

imjp


1 Answers

Assuming that in addition to your @models which contains the full list, you also have @model which contains the current record, then you can do the following:

<%= 
  select_tag "name_dropdown", 
  options_from_collection_for_select(@models, "friendly_id", "name", @model.id) 
%>

Basically, the fourth parameter to options_from_collection_for_select(...) should contain the id of the item you want to be selected. Your second code sample forces the selected id to be 1 every time, and the third sample you posted always makes the first item in @models selected, regardless of the actual currently selected model.

like image 121
Dylan Markow Avatar answered Oct 24 '22 10:10

Dylan Markow