我需要在<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"
添加到选项列表的方法?
答案 0 :(得分:9)
<%= f.select(:parent_id, [["==None==", 0]] + @parent_menus.collect {|p| [ p.name, p.id ] }) %>
答案 1 :(得分:1)
尝试
<%= f.select(:parent_id, options_for_select(["==None==", 0] + @parent_menus.collect {|p| [ p.name, p.id ] }, 0)) %>
答案 2 :(得分:1)
我想我会把这个添加到任何想要做默认选择值的人,这是下拉列表中的一个对象,而不是'none'值。即,您正在编辑已选择上一个值的表单,并且您不希望在编辑页面上丢失该先前值:
假设您在@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)
答案 3 :(得分: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 ))%>