【问题标题】:Rails select_tag - Setting include_blank and selecting a default valueRails select_tag - 设置 include_blank 并选择默认值
【发布时间】:2011-06-24 03:17:58
【问题描述】:
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 =&gt; 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 } %>

上面总是选择“选择一个国家”。

为什么?

【问题讨论】:

    标签: ruby-on-rails-3 forms


    【解决方案1】:

    空白值

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

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

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

    选定值

    因为select_tag 不属于对象,就像select 一样,您需要将选定的值指定为选项的一部分。将选定的值传递给select_tag 的options 参数。

    在您的情况下,您使用options_from_collection_for_select 来帮助生成这些选项。此方法采用第四个参数,指定应选择哪个选项。

    options_from_collection_for_select( 
      Country.order('priority desc, name asc'), 
      :id, 
      :name,
      Country.find_by_name('Canada')
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多