显示复选框列表而不是多选
我有一个带有序列化属性 a
的模型 MyModel
,描述了一个符号数组.
I have a model MyModel
with a serialized attribute a
, describing an array of symbols.
此代码有效:
<% form_for @my_model do |f| %>
<%= f.select :a, MyModel::AS, :multiple => true) %>
<% end %>
参数正确:
{ :my_model => { :a => [:a_value1, :a_value2] } }
我想将这个多选转换成一组复选框,如下所示:
I want to transform this multiple select into a set of checkboxes, like this :
<% form_for @my_model do |f| %>
<% MyModel::AS.each do |a_value|
<%= f.check_box(:a_value) %>
<% end %>
<% end %>
它也能用,但参数根本不一样:
It works too, but the parameters are not the same at all :
{ :my_model => { :a_value1 => 1, :a_value2 => 1 } }
我想到了两个解决方案,回到第一个解决方案......
I think of 2 solutions to return to the first solution...
- 将我的
check_box
转换为check_box_tag
,替换多个选择,并添加一些 javascript 以在用户单击 check_box_tags 时检查"选择值.然后,参数将直接在控制器中相同. - 在控制器中添加一小段代码以调整"我的参数.
- Transform my
check_box
intocheck_box_tag
, replace multiple select, and add some javascript to 'check' select values when user clic on check_box_tags. Then, the parameter will be the same directly in the controller. - Add a litte code into the controller for 'adapting' my params.
什么解决方案不那么难看?或者还有别的吗?
What solution is the less ugly ? Or is there any other one ?
我找到了一个解决方案,使用了我不知道的multiple"选项.
I found a solution, using 'multiple' option that I didn't know.
<% MyModel::AS.each do |a_value| %>
<%= f.check_box(:a, { :multiple => true }, a_value) %>
<% end %>
结果参数有点奇怪,但应该可以.
Result parameters are a little weird, but it should work.
{"my_model" => { "a" => ["0", "a_value1", "0", "a_value2", "0"] }
从@Viren 在函数末尾传递 nil
像
Edit from @Viren : passing nil
at the end of the function like
<%= f.check_box(:a, { :multiple => true }, a_value, nil) %>
完美运行.