Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display selected option when editing a form (Rails 4)

I want to display my dropdown form selected option value whenever an user edits the form. Right now it displays the first option (in this case a blank option).

Form

<%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]]), :include_blank => true, :selected => params[:condition]) %>

HTML Output

<select id="product_condition" name="product[condition]">
    <option value=""></option>
    <option value="Brand New">Brand New</option>
    <option value="Pre-owned">Pre-owned</option>
</select>

JSON

{
    id: 2,
    condition: "Pre-owned",
}

Thanks.

like image 341
chrisbedoya Avatar asked Feb 02 '15 21:02

chrisbedoya


2 Answers

<%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]], :selected => f.object.condition), :include_blank => true) %>
like image 189
chrisbedoya Avatar answered Oct 16 '22 16:10

chrisbedoya


Check the options_for_select documentation, and you will discover that the last parameter is the selected option.

options_for_select(container, selected = nil)

In your case

<%= f.select(:condition, options_for_select([["Brand New", "Brand New"], ["Pre-owned", "Pre-owned"]], params[:condition]), :include_blank => true) %>

assuming params[:condition] contains the currently selected value, and the value matches the corresponding value in the select tag.

In other words, for "Pre-owned" to be selected, params[:condition] must contain "Pre-owned".

like image 29
Simone Carletti Avatar answered Oct 16 '22 15:10

Simone Carletti