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'
除外。呈现空白选项。像这样:
<option value=""></option>
第二,使用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 } %>
上面总是选择“选择一个国家”。
为什么?
发布于 2015-06-15 20:53:51
空白值
我不认为这在其他帖子上得到了足够的关注:
include_blank
on select_tag
不尊重传递给它的字符串。它只将其解释为一个true
**/**false
值.。
为了用特定的字符串为select_tag
设置一个空白值,您需要使用prompt
。
选定值
因为select_tag
不属于一个对象,所以按照select
的方式,您需要将选定的值指定为选项的一部分。将选定的值传递到select_tag
的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')
)
https://stackoverflow.com/questions/6462956
复制相似问题