显示复选框列表而不是多选 [英] Display a checkbox list instead of multiple select

查看:43
本文介绍了显示复选框列表而不是多选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有序列化属性 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 into check_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) %>

完美运行.

这篇关于显示复选框列表而不是多选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆