Rails4 collection_select包含数据选项

时间:2014-06-21 06:51:51

标签: ruby-on-rails ruby-on-rails-4 dropdownbox collection-select

我想使用FormHelper

重现以下选择结构
<select data-placeholder="Choose a Country..." name="select2" class="required select">
            <option value=""></option>
            <option value="opt2">India</option>
            <option value="opt2">United States of America</option>
          </select>

我尝试了什么?

    <%= f.collection_select(:country_id, @countries, :id, :name, { :prompt => true }, 
{ :class => 'select', :selected => params[:country_id], :date => {:placeholder => 'Choose a Country...' }}) %>

但是Placeholder标记没有被选中,它显示Please Select

2 个答案:

答案 0 :(得分:1)

此:

= collection_select("user", "country_id", @countries, :id, :name, {:prompt => true}, { :class => 'select', :selected => 1, "data-placeholder" => 'Choose a Country...' })

返回此html(我添加user进行测试):

<select class="select" data-placeholder="Choose a Country..." id="user_country_id" name="user[country_id]" selected="selected"><option value="">Please select</option>
<option value="1">Russia</option>
<option value="2">USA</option></select>

所以这就是你所期望的,但对我而言,它并没有显示占位符。要显示它,只需将prompt更改为占位符标题:

f.collection_select(:country_id, @countries, :id, :name, {:prompt => 'Choose a Country...'}, { :class => 'select', :selected => params[:country_id])

这对我来说很好。

答案 1 :(得分:1)

来自rails文档

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

根据语法:selected参数应该进入options而不是html_options

您需要做的就是从:selected中移除html_options参数并将其包含在options

 <%= f.collection_select(:country_id, @countries, :id, :name, { :prompt => true, :selected => params[:country_id] }, { :class => 'select', :date => {:placeholder => 'Choose a Country...' }}) %>