how to set default value of form_for select

前端 未结 2 1524
花落未央
花落未央 2021-01-12 20:17

I would like to know how to set default value on form_for select.

My code goes like this:

<%= form_for(@user) do |f| %>
 .
 .
 .

 
相关标签:
2条回答
  • 2021-01-12 20:51

    Add a parameter :selected =>

        <%= form_for(@user) do |f| %>
         .
         .
         .
    
         <div class="field">
         <%= f.select(:user_group_id, options_for_select(@user_groups.collect {|p| [ p.name, p.id ] },   "Select Category"), :selected =>f.object.user_group_id) %>
         </div>
        <%= end %>
    
    0 讨论(0)
  • 2021-01-12 20:53

    You can pass a second option to options_for_select that indicates the selected value.

    options_for_select(@user_groups.collect { |p| [p.name, p.id] }, @user.user_group)
    

    Obviously I'm not sure how your models are set up, but if necessary you use a method like find to locate the entry you want.

    0 讨论(0)
提交回复
热议问题