Display a checkbox list instead of multiple select

纵然是瞬间 提交于 2019-11-29 02:52:21

问题


I have a model MyModel with a serialized attribute a, describing an array of symbols.

This code works :

<% form_for @my_model do |f| %>
  <%= f.select :a, MyModel::AS, :multiple => true) %>
<% end %>

The parameters are correct :

{ :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...

  • 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 ?


回答1:


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"] }

Edit from @Viren : passing nil at the end of the function like

  <%= f.check_box(:a, { :multiple => true }, a_value, nil) %>

works perfectly.




回答2:


There is another solution worth mentioning that makes it very easy to insert records into the database if you have a has_and_belongs_to_many or has_many through relationship by using the collection_check_boxes form helper. See documentation here.

<%= f.collection_check_boxes :mymodel_ids, MyModel::AS, :id, :name do |m| %>
  <%= m.check_box %> <%= m.label %>
<% end %>

Then, in the controller we would allow the mymodel_ids attribute:

params.require(:mymodel).permit(:name, mymodel_ids:[])

We can also set up a model validation to require that at least one of the checkboxes be checked:

validates :mymodel_ids, presence: true

An added benefit of this method is that if you later edit the mymodel record and uncheck one of the checkboxes, its record will be deleted from the many_to_many association table on save.




回答3:


You can do it like this:

<% MyModel::AS.each do |a_value| %>
  <%= f.check_box("a[]", a_value) %>  
<% end %>

This will make params come to server as follows

{ :my_model => { :a => [:a_value1, :a_value2] } }


来源:https://stackoverflow.com/questions/15899550/display-a-checkbox-list-instead-of-multiple-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!