Rails form_for multiple collection_select,在表单失败时未选择值

时间:2015-06-15 02:06:28

标签: ruby-on-rails

我不知道为什么,但我的表单没有显示提交时选择的选项,即使params哈希显示信息正在返回到页面。

收藏选择代码:

<%= f.collection_select :post_topic_ids, PostTopic.all, :id, :name, {}, { multiple: true, class: 'form-control' } %>

呈现:

<select multiple="multiple" class="form-control" name="post[post_topic_ids][]" id="post_post_topic_ids">
  <option value="1">Psychology</option>
  <option value="2">Engineering</option>
  <option value="3">Nanotechnology</option>
</select>

表单验证错误

后返回Params
params = {"post"=>{"post_topic_ids"=>["", "1"]}}

更新

我也尝试过:

<%= select_tag 'post_topic_ids', options_for_select(PostTopic.all.collect{ |p| [p.name, p.id] }), multiple: true %>

<%= select_tag 'post_topic_ids', options_from_collection_for_select(PostTopic.all, "id", "name"), multiple: true %>

呈现:

<select name="post_topic_ids[]" id="post_topic_ids" multiple="multiple"><option value="1">Psychology</option>
<option value="2">Engineering</option>
<option value="3">Nanotechnology</option></select>

1 个答案:

答案 0 :(得分:1)

您需要指定选择哪个元素作为第三个参数

<%= select_tag 'post_topic_ids', options_for_select(PostTopic.all.collect{ |p| [p.name, p.id] }, --->selected_element<---), multiple: true %>

查看http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select的一些示例。