Rails 4: Display selected value on edit in dropdown

3.6k Views Asked by At

I have an f.select in the new article page, and it works fine. However, when I edit the article, the value changes back to whatever is first in the options.

Is there a way to keep the select value so users don't have to worry about redoing that when editing their article?

Here is my select tag:

<%= f.select :category, 
    options_for_select(['drink','food','medicine','supplement','drug','ingredient','lifestyle','other'], params[:category]), {}, { :class => 'span3 controls controls-row' } %>
2

There are 2 best solutions below

0
On BEST ANSWER

Instead of params[:category] you should provide selected: :category in the options_for_select(<...>).

0
On

Change:

<%= f.select :category,   options_for_select(['drink','food','medicine','supplement','drug','ingredient','lifestyle','other'], params[:category]), {}, { :class => 'span3 controls controls-row' } %>

to:

<%= f.select :category, options_for_select(['Mare', 'Stallion', 'Gelding'], :selected => f.object.category), {}, { :class => 'span3 controls controls-row' } %>

which is similar to what is here: https://stackoverflow.com/a/19120874/3507417