Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails' collection_select helper method and the "Create item" option at the end

Is it possible to add an <option> at the end of a <select> created with the collection_select helper method?

Right now I have

f.collection_select(:category_id , @categories, :id, :name, {:prompt => 'Please select a category'})

which generates

<select id="product_category_id" name="product[category_id]">
  <option value="">Please select a category</option>
  <option value="7">category one</option>
  <option value="8">category 2</option>
</select>

and what I would like is

<select id="product_category_id" name="product[category_id]">
  <option value="">Please select a category</option>
  <option value="7">category one</option>
  <option value="8">category 2</option>
  <option value="new">..or create a new one</option>
</select>

Is this possible or should I just loop through the collection and generate the options manually?

like image 253
andi Avatar asked Mar 30 '09 21:03

andi


1 Answers

You should probably use select instead.

Like so:

f.select(:category_id, @categories.collect {|p| [ p.name, p.id ] } + [ [ 'Or create a new one', 'new' ] ], {:include_blank => 'Please select a category'})

Good luck!

like image 54
Gdeglin Avatar answered Nov 15 '22 17:11

Gdeglin