Rails: Adding options to collection_select

Almaron picture Almaron · May 4, 2012 · Viewed 8.1k times · Source

I am using a collection_select field, but need to prepend the options with some default one, wich does not represent a particular model record and is used to set the appropriet field to NULL. But I just can't find any way to do that.

If you need any more information, don't hasitate to ask. Using Rails 3.2.3 with standard form helpers.

P.S. I know I can do something like this:

@parents = ['default_name','nil']
@parents << Model.all.map {|item| [item.name,item.id]}

But I think there is a more elegant way.

Answer

Simon Perepelitsa picture Simon Perepelitsa · May 4, 2012

There is an :include_blank option you can pass to collection_select helper method:

f.collection_select(:author_id, Author.all, :id, :name_with_initial,
                    :include_blank => "Nothing selected")

There is also a similar option called :prompt, check it out too.