我尝试了:include_blank => true
,但它没有用。
<select>
<%= options_for_select Model.all.collect{|mt| [mt.name, mt.id]} %>
</select>
如果我需要将它添加到集合中,你会怎么做?
答案 0 :(得分:82)
我想你想要这种格式:
select("model_name", "model_id", Model.all.collect {|mt| [ mt.name, mt.id ] }, {:include_blank => 'name of your blank prompt'})
BTW:假设Model应该是Model。要使用collection_select:
collection_select(:model, :model_id, Model.all, :id, :name, :prompt => true)
答案 1 :(得分:25)
我认为:include_blank
选项仅适用于与模型相关联的select
字段。
假设您要使用普通<select>
标记而不是绑定到模型的<%= select(...) %>
标记,则可以在结果的前面插入空白条目:
<%= options_for_select Modle.all.collect{|mt| [mt.name, mt.id]}.insert(0, "") %>
答案 2 :(得分:17)
由于您已标记为select-tag,因此可以使用include_blank
选项select_tag
。
来自文档:
select_tag "people", options_from_collection_for_select(@people, "id", "name"), :include_blank => true
# => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
或者您可以使用options_for_select
:
<%= select_tag column.name, options_for_select(Model.all.collect{|mt| [mt.name, mt.id]}), :include_blank => true %>
答案 3 :(得分:6)
<%= options_for_select Model.all.collect{|x| [x.name,x.id]}.unshift(["",nil]) %>
答案 4 :(得分:1)
= select_tag "some_value", options_for_select(Model.all.collect{ |x| [x.name, x.id]}.prepend([t('helpers.some_name'), nil]), :selected => params[:some_value])
答案 5 :(得分:1)
如果你想要一个光滑的解决方案,你可以使用我的宝石rearmed_rails
,其中有一个功能可以安全地修补补丁options_for_select
和options_for_collection_select
rails g rearmed_rails:setup
打开config/initializers/rearmed_rails.rb
并将以下值更改为true
options_for_select_include_blank: true,
options_from_collection_for_select_include_blank: true
现在,无论何时需要空白,只需执行以下操作:
<%= options_for_select(Model.all.map{|x| [x.name,x.id]}, include_blank: true) %>