开发者

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?


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')
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜