簡體   English   中英

Rails form_for multiple collection_select,表單失敗時未選擇值

[英]Rails form_for multiple collection_select, values not selected on form failure

我不知道為什么,但我的表單沒有顯示提交時選擇的選項,即使 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 = {"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>

您需要指定選擇哪個元素的第三個參數

<%= 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以獲取一些示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM