Rails 5 form_for with checkbox array Rails 5 form_for with checkbox array postgresql postgresql

Rails 5 form_for with checkbox array


There's a collection_check_boxes helper method for this:

<%= form_for @course do |f| %>  <%= f.collection_check_boxes(:level, { 'One': 1, 'Two': 2, 'Three': 3 }, :last, :first) %><% end %>

The third argument is the method used to get the value from the "collection", and the fourth is the method used to get the label from the "collection". This helper method automatically converts the Hash into an array, that's why I'm using last and first here.

It's also possible to style it the way you want e.g. using Bootstrap:

<%= f.collection_check_boxes(:level, { 'One': 1, 'Two': 2, 'Three': 3 }, :last, :first) do |b| %>  <div class="form-check form-check-inline">    <%= b.check_box class: 'form-check-input' %>    <%= b.label class: 'form-check-label' %>  </div><% end %>


<%= check_box_tag 'level[]', 1%><%= check_box_tag 'level[]', 2%><%= check_box_tag 'level[]', 3%><%= check_box_tag 'level[]', 4%>

But when you use check_box_tags in form_for, then the parameters level[], will be outside off the strong parameters array you usually use in the controller#new function.

Parameters: {"course"=>{"number"=>"12", "name"=>"tanzen", "description"=>"efwefggw", "max_visitor"=>"12", "min_visitor"=>"5", "pos_visit"=>"2"}, "level"=>["1", "3", "4"], "commit"=>"bestätigen"}

So I added the level manually

@course = Course.new(course_params)@course.level = params[:level]