Rails:向collection_select添加选项

Alm*_*ron 6 form-helpers ruby-on-rails-3

我正在使用collection_select字段,但是需要在默认选项前添加选项,这些选项不代表特定的模型记录,用于将appropriet字段设置为NULL.但我无法找到任何办法.

如果您需要更多信息,请不要随便询问.使用Rails 3.2.3与标准表单助手.

PS我知道我可以这样做:

@parents = ['default_name','nil']
@parents << Model.all.map {|item| [item.name,item.id]}
Run Code Online (Sandbox Code Playgroud)

但我认为有更优雅的方式.

Sim*_*tsa 15

有一个:include_blank选项,您可以传递给collection_select帮助方法:

f.collection_select(:author_id, Author.all, :id, :name_with_initial,
                    :include_blank => "Nothing selected")
Run Code Online (Sandbox Code Playgroud)

还有一个类似的选项叫做:提示,也可以查看.


小智 11

您可以使用select代替:

f.select(:item_id, @items.collect {|p| [ p.name, p.id ] } + ['Or create a new one like','new'], {:include_blank => 'Please select a item'})
Run Code Online (Sandbox Code Playgroud)