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
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 ?
You can do it like this:
This will make params come to server as follows
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
orhas_many
through
relationship by using thecollection_check_boxes
form helper. See documentation here.Then, in the controller we would allow the
mymodel_ids
attribute:We can also set up a model validation to require that at least one of the checkboxes be checked:
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 themany_to_many
association table onsave
.I found a solution, using 'multiple' option that I didn't know.
Result parameters are a little weird, but it should work.
Edit from @Viren : passing
nil
at the end of the function likeworks perfectly.