Rails select_tag - 设置include_blank并选择默认值

Chr*_*ini 7 forms ruby-on-rails-3

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

如预期的那样,除了:include_blank => 'None'.呈现空白选项.像这样:

<option value=""></option>
Run Code Online (Sandbox Code Playgroud)

第二,与select_tag.如何指定默认值.例如,如果我需要选择框来选择特定国家/地区.我尝试添加:selected => Country.first无济于事:

<%= 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 } %>
Run Code Online (Sandbox Code Playgroud)

以上始终选择"选择国家/地区".

为什么?

Jos*_*ter 3

空白值

我认为这在其他帖子上没有得到足够的关注:

include_blankon aselect_tag不尊重传递给它的字符串。它仅将其解释为true/false值。

为了select_tag使用特定字符串设置空白值,您需要使用prompt.

选定值

因为select_tag不属于对象,所以select您需要将所选值指定为选项的一部分。将选定的值传递到options的参数中select_tag

就您而言,您正在使用options_from_collection_for_select来帮助生成这些选项。此方法采用第四个参数来指定应选择哪个选项。

options_from_collection_for_select( 
  Country.order('priority desc, name asc'), 
  :id, 
  :name,
  Country.find_by_name('Canada')
)
Run Code Online (Sandbox Code Playgroud)