ruby-on-railsruby-on-rails-2

Display a checkbox list instead of multiple select


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

What solution is the less ugly ? Or is there any other one ?


Solution

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