Almaron
Almaron

Reputation: 4147

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.

Upvotes: 6

Views: 8855

Answers (3)

Simon Perepelitsa
Simon Perepelitsa

Reputation: 20649

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.

Upvotes: 16

swati
swati

Reputation: 1757

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'})

Upvotes: 11

Matzi
Matzi

Reputation: 13925

Something like this is acceptable in your view?

collection_select :field1, :field2, @models+[Model.new(name: "default_name")], :name, :id

Upvotes: 2

Related Questions