Ruby on rails 3 Rails select_标记-设置包括_blank并选择默认值
按预期执行,除了Ruby on rails 3 Rails select_标记-设置包括_blank并选择默认值,ruby-on-rails-3,forms,Ruby On Rails 3,Forms,按预期执行,除了:include_blank=>“None”。呈现空白选项。例如: select_tag :country_id, options_from_collection_for_select(Country.order('priority desc, name asc'), "id", "name"), { :prompt => 'Select a country', :include_blank => 'None' } %> 上面总是选择“选择一个国家” 为什么
:include_blank=>“None”
。呈现空白选项。例如:
select_tag :country_id, options_from_collection_for_select(Country.order('priority desc, name asc'), "id", "name"), { :prompt => 'Select a country', :include_blank => 'None' } %>
上面总是选择“选择一个国家”
为什么?空白值
我认为这在其他帖子上没有引起足够的关注:
在选择标记
上包含空白
不尊重传递给它的字符串。它仅将其解释为true
/false
值。
要使用特定字符串为select_tag
设置空白值,需要使用prompt
选定值
由于select\u tag
不属于对象,因此需要按照select
的方式指定所选值作为选项的一部分。将所选值传递到选择标签
的选项
参数中
在您的案例中,您正在使用来自\u集合\u的options\u进行\u选择
以帮助生成这些选项。此方法采用第四个参数,该参数指定应选择哪个选项
<%= 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 } %>
<%= 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 } %>
options_from_collection_for_select(
Country.order('priority desc, name asc'),
:id,
:name,
Country.find_by_name('Canada')
)