2010-11-29 59 views
2

「collection_select,多=>真正的」多「check_box」選項如何更換collection_select(與:multiple => true)帶的check_box選項,列表使得存在在每個對象check_box選項採集?替換:在Rails的

是否有優雅使用表單構建器實現此目的的方法(即不使用*_tag助手)?我想盡可能地依靠ActiveRecord的內置功能...

回答

0

你可以做這樣的(使用HAML例子)。

%fieldset 
    Colors I like 
    - %w[red blue].each do |color| 
    = f.label color 
    = f.check_box :colors_liked, {multiple: true}, color, nil 

末的nil選項防止滑軌從同名0值,這你絕對,如果你要爲多選不希望建立一個隱藏的複選框。

這產生:

<label for="colors_liked_red">Red</label> 
<input id="my_form_colors_liked_red" \ 
    name="my_form[colors_liked][]" type="checkbox" value="red"> 

<label for="colors_liked_blue">Blue</label> 
<input id="my_form_colors_liked_blue" \ 
    name="my_form[colors_liked][]" type="checkbox" value="blue"> 

當表單提交,這些參數將包含的檢查選項的值的數組。