Display a checkbox list instead of multiple select

pierallard picture pierallard · Apr 9, 2013 · Viewed 31.3k times · Source

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 ?

Answer

pierallard picture pierallard · Apr 9, 2013

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.