简体   繁体   中英

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.

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

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" .

<%= form.label :Hobbies%>

<%= form.select(:hobbies, options_for_select(%w[cricket football hockey 
reading], :selected => form.object.hobbies )) %><br><br>

This form multiple drop down but user only select one and if you edit and show method show only one record.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM