Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Adding options to collection_select

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.

like image 935
Almaron Avatar asked May 04 '12 12:05

Almaron


2 Answers

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.

like image 172
Simon Perepelitsa Avatar answered Oct 05 '22 10:10

Simon Perepelitsa


You can probably use select instead :

f.select(:item_id, @items.collect {|p| [ p.name, p.id ] } + ['Or create a new one like','new'], {:include_blank => 'Please select a item'})
like image 42
swati Avatar answered Oct 05 '22 10:10

swati