How to set "selected" in select_tag/options_from_collection_for_select

Viewed 19451

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

2 Answers

Throwing this answer here for people that are within a form block, because I too lost more time on this than I wish.

This example is particularly if you have a relationship like a belongs_to, because you will also need to explicitly state that it is the id you are updating rather than updating with a related object/instance. Otherwise you can end up with an ActiveRecord::AssociationTypeMismatch: RelatedModel expected, got "#" which is an instance of String.

<%=
  f.select :related_model_id,
    options_from_collection_for_select(
      RelatedModel.all, :id, :name, f.object.related_model_id)
%>
Related