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?
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
.
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')
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With