2012-07-27 52 views
20

下面是我的选择表单,它可以正常工作。如何将'select one ...'添加到options_from_collection_for_select

当用户加载页面时,它应该显示一个初始'select one ...',其值为null或''。

我试图将它添加到对象,但无法并且很乐意获得帮助!

非常感谢!


笔者认为:

= select_tag 'incident[fault_id]' , options_from_collection_for_select(Fault.all, :id, :label) 

我使用的Rails 3.2和HAML


更新:

一次偶然的机会我发现了一些真甜:

include_blank: 'select one...' 

或完全

= f.collection_select :fault_id, Fault.order(:label), :id, :label, include_blank: 'select one...' 

如果一个喜欢太...

参考:http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

+0

您可以将您的“内联”答案移至问题的真实答案,以便人们可以投票支持。不幸的是:include_blank或:prompt只能用于rails 3.x + – rogerdpack 2014-12-07 06:20:29

回答

38

options_from_collection_for_select返回选项标签的字符串已被遍历编译将值调用的结果作为选项值并将text_method作为选项文本分配给value_method。

所以只是 “select_one” 选项字符串前面加上它没有价值:

= select_tag 'incident[fault_id]', content_tag(:option,'select one...',:value=>"")+options_from_collection_for_select(Fault.all, :id, :label) 
+0

非常感谢!这很容易,如果你知道它... – 2012-07-27 13:13:40

+1

甜终于一个选项,与钢筋2.x与3.x使用:include_blank或什么不相信... – rogerdpack 2014-12-07 06:20:55

+1

虽然这工作,它会更正确的使用'提示'选项,如下所述。 – 2015-05-12 06:21:22

19

:promptselect_tagoptions_from_collect_for_select一个属性,以便

select_tag("sales_rep[manufacturer_id]", options_from_collection_for_select(@manufacturers, "id", "name"), { :prompt => 'Select Manufacturer' }) 
0

你可以尝试以下方法:

collection_select(:sales_rep, :manufacturer_id, @manufacturers, :id, :name, { :prompt => 'Select Manufacturer' }) 
相关问题