2015-06-15 58 views
1

我不確定爲什麼,但我的表單不顯示提交時選擇的選項,即使params散列顯示信息正在返回到頁面。Rails form_for multiple collection_select,未在表單失敗時選擇的值

款式選擇代碼:

<%= 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 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> 
+0

我的'表單沒有顯示提交時選擇的選項'是什麼意思? – Pavan

+0

對不起我的意思是當表單重新加載時沒有選擇選項...表單提交失敗後,由於驗證錯誤 – Abram

+0

好的。我明白了。請發佈您的控制器代碼。 – Pavan

回答

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

+0

我使用了<%= f.collection_select:post_topic_ids,PostTopic.all,:id,:name,{:selected => @ post.post_topic_ids},{multiple:true,class:'form-control'}% > – Abram

+0

我通常使用simple_form,這非常容易.. – Abram