Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails select_tag - Setting include_blank and selecting a 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' } %> 

Does as expected, except :include_blank => 'None'. Renders an blank option. Like such:

<option value=""></option>

Second, with the select_tag. How do I specify a default value. For example, if I need the select box to select a specific country. I tried adding :selected => Country.first to 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 selects "Select a country".

Why?

like image 593
Christian Fazzini Avatar asked Jun 24 '11 03:06

Christian Fazzini


1 Answers

Blank Value

I don't think this is getting enough attention on other posts:

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

In order to set a blank value for select_tag with a specific string, you need to use prompt.

Selected Value

Because select_tag does not belong to a object, the way select does, you need to specify the selected value as part of the options. pass the selected value into the options param of the select_tag.

In your case, you are using options_from_collection_for_select to help generate those options. This method takes a fourth parameter that specifies which option should be selected.

options_from_collection_for_select( 
  Country.order('priority desc, name asc'), 
  :id, 
  :name,
  Country.find_by_name('Canada')
)
like image 120
Joshua Pinter Avatar answered Oct 30 '22 08:10

Joshua Pinter