开发者

how to set default value of form_for select

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

My code goes like this:

<%= form_for(@us开发者_StackOverflower) do |f| %>
 .
 .
 .

 <div class="field">
 <%= f.select(:user_group_id, options_for_select(@user_groups.collect {|p| [ p.name, p.id ] },   "Select Category")) %>
 </div>
<%= end %>

Obviously it would return all the values of the field user_group. On my edit page, I would like to set the default value to whatever value the user have in the user_group. Pls help


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜