Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include blank for first item in select list in options_for_select tag

I tried :include_blank => true, but it didn't work.

<select>
    <%= options_for_select Model.all.collect{|mt| [mt.name, mt.id]} %>
</select>

If I need to add it to the collection, how would you do that?

like image 877
B Seven Avatar asked Jul 15 '11 17:07

B Seven


3 Answers

I think you want this format:

select("model_name", "model_id", Model.all.collect {|mt| [ mt.name, mt.id ] }, {:include_blank => 'name of your blank prompt'})

BTW: was assuming Modle was suppose to be Model. To use using collection_select:

collection_select(:model, :model_id, Model.all, :id, :name, :prompt => true)
like image 118
Chris Barretto Avatar answered Oct 21 '22 06:10

Chris Barretto


I believe the :include_blank options only exist for select fields tied to a model.

Assuming you want to use a plain <select> tag instead of a <%= select(...) %> tied to a model, you can insert a blank entry at the front of your results:

<%= options_for_select Modle.all.collect{|mt| [mt.name, mt.id]}.insert(0, "") %>
like image 21
Dylan Markow Avatar answered Oct 21 '22 08:10

Dylan Markow


Since you have tagged as select-tag you can use the option include_blank with select_tag.

From the documentation:

select_tag "people", options_from_collection_for_select(@people, "id", "name"), :include_blank => true

# => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>

Or you can use options_for_select:

<%= select_tag column.name, options_for_select(Model.all.collect{|mt| [mt.name, mt.id]}), :include_blank => true %>
like image 26
Paulo Fidalgo Avatar answered Oct 21 '22 08:10

Paulo Fidalgo