7

我想知道如何在 form_for select 上设置默认值。

我的代码是这样的:

<%= 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")) %>
 </div>
<%= end %>

显然它将返回字段 user_group 的所有值。在我的编辑页面上,我想将默认值设置为用户在 user_group 中的任何值。请帮忙

4

2 回答 2

12

您可以传递第二个选项来options_for_select指示所选

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

显然,我不确定您的模型是如何设置的,但如果有必要,您可以使用find之类的方法来定位您想要的条目。

于 2011-03-07T06:21:45.730 回答
1

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 %>
于 2012-01-26T10:37:57.610 回答