2

我想使用 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...' }}) %>

但是占位符标签没有被拾起,它显示Please Select

4

2 回答 2

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...' }}) %>
于 2014-06-21T07:43:56.327 回答
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])

这对我来说很好。

于 2014-06-21T07:22:37.320 回答