6

我需要在列表中生成一个带有默认值的选择菜单<options>。这是我需要的样子。

<select name="menu[parent_id]" id="menu_parent_id">
 <option value="0">==None==</option>
 <option value="34">TEST</option>
</select>

目前我select在我的表单中使用这个助手

   <%= f.select(:parent_id, @parent_menus.collect {|p| [ p.name, p.id ] }, {:include_blank => '==None=='})%>

上面的代码产生了这个;( value="")

<select name="menu[parent_id]" id="menu_parent_id">
 <option value="">==None==</option>
 <option value="34">TEST</option>
</select>

这里有没有人可以告诉我一种添加value="0"到选项列表的方法?

4

4 回答 4

9
<%= f.select(:parent_id, [["==None==", 0]] + @parent_menus.collect {|p| [ p.name, p.id ] }) %>
于 2010-05-05T10:02:40.203 回答
1

尝试

<%= f.select(:parent_id, options_for_select(["==None==", 0] + @parent_menus.collect {|p| [ p.name, p.id ] }, 0)) %>
于 2010-05-05T10:39:08.773 回答
1

以为我会将其添加给任何希望执行默认选定值的人,该值是下拉列表中的对象之一,而不是“无”值。即,您正在编辑一个选择了先前值的表单,并且您不想在编辑页面上丢失该先前值:

假设您在@parents 中有一组父母,并且您的表单与名为@my_messed_up_family 的对象相关联,并且@my_messed_up_family 有一个“父亲”:

= f.label :parent_id, "Choose which of your parents is your father?

= f.select :parent_id, options_from_collection_for_select(@parents.sort_by {|n| n.name}, "id", "name", :selected=>@my_messed_up_family.father.id)
于 2012-10-03T15:36:30.803 回答
0

我不知道这是否是 Ruby 方式,但这肯定会起作用

<%= f.select(:parent_id, "<option value='0'>Please select</option>"+options_for_select(@parent_menus.collect {|p| [ p.name, p.id ] }))%>

已编辑。对于根据保存在数据库中的值预先选择,我假设@user 是您的对象,包含以下示例的数据库值。

<%= f.select(:parent_id, "<option value='0'>Please select</option>"+options_for_select(@parent_menus.collect {|p| [ p.name, p.id ] }, @user.id ))%>
于 2010-05-05T11:09:54.580 回答