Rails select_tag - setting include_blank and selecting the default value

select_tag :country_id, options_from_collection_for_select(Country.order('priority desc, name asc'), "id", "name"), { :prompt => 'Select a country', :include_blank => 'None' } %> 

It does as expected, except for :include_blank => 'None' . Displays an empty parameter. For example:

 <option value=""></option> 

Secondly, with select_tag . How to specify a default value. For example, if I need a selection box to select a specific country. I tried adding :selected => Country.first no avail:

 <%= select_tag :country_id, options_from_collection_for_select(Country.order('priority desc, name asc'), "id", "name"), { :prompt => 'Select` a country', :include_blank => 'None', :selected => Country.first } %> 

Above, always select "Select Country".

Why?

+7
source share
1 answer

Empty value

I don't think this pays enough attention to other posts:

include_blank on select_tag does not support the string passed to it. It only interprets it as true / false .

To set an empty value for select_tag with a specific string, you need to use prompt .

Selected value

Since select_tag does not belong to the object, the select method, you need to specify the selected value as part of the parameters. pass the selected value to the options parameter of the select_tag parameter.

In your case, you use options_from_collection_for_select to help generate these parameters. This method accepts a fourth parameter , which indicates which parameter should be selected.

 options_from_collection_for_select( Country.order('priority desc, name asc'), :id, :name, Country.find_by_name('Canada') ) 
+3
source

All Articles