24

下面是我的选择表单,它可以正常工作。

当用户加载页面时,它应显示初始“选择一个...”,值为 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

4

3 回答 3

44

options_from_collection_for_select返回一个选项标记字符串,这些选项标记已通过迭代集合并将调用结果分配给 value_method 作为选项值和 text_method 作为选项文本来编译。

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

 = select_tag 'incident[fault_id]', content_tag(:option,'select one...',:value=>"")+options_from_collection_for_select( Fault.all, :id, :label)
于 2012-07-27T09:09:37.330 回答
26

:promptselect_tag 不是options_from_collect_for_select这样的属性

select_tag("sales_rep[manufacturer_id]", options_from_collection_for_select(@manufacturers, "id", "name"), { :prompt => 'Select Manufacturer' })
于 2013-10-03T21:46:27.457 回答
0

您可以尝试以下方法:

collection_select(:sales_rep, :manufacturer_id, @manufacturers, :id, :name, { :prompt => 'Select Manufacturer' })
于 2015-07-20T13:14:33.257 回答