在options_for_select标签的select列表中为第一个项目添加空白
我试过:include_blank => true
,但它没有工作。
<select> <%= options_for_select Model.all.collect{|mt| [mt.name, mt.id]} %> </select>
如果我需要将它添加到集合中,你将如何做到这一点?
我想你想要这种格式:
select("model_name", "model_id", Model.all.collect {|mt| [ mt.name, mt.id ] }, {:include_blank => 'name of your blank prompt'})
顺便说一句:假设莫德假设是模型。 要使用collection_select:
collection_select(:model, :model_id, Model.all, :id, :name, :prompt => true)
我相信:include_blank
选项仅适用于与模型绑定的select
字段。
假设您想要使用简单的<select>
标签而不是与模型绑定的<%= select(...) %>
,您可以在结果的前面插入空白条目:
<%= options_for_select Modle.all.collect{|mt| [mt.name, mt.id]}.insert(0, "") %>
由于您已将标签标记为select标签,因此您可以使用选项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 %>
<%= options_for_select Model.all.collect{|x| [x.name,x.id]}.unshift(["",nil]) %>
= 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])
如果你想要一个光滑的解决scheme,你可以使用我的gemrearmed_rails
有一个function,安全地猴子修补程序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) %>