Rails foundationSort Order

Rails: Collection Check Boxes

In this episode we show you how to implement check boxes for the tags. We also talk about how to permit array values in strong parameters in our controller.

Assigning Relationships with ID

With many-to-many relationships we can assign tags to post by using the id as well. Let's try it out

post = Post.firstpost.tag_ids = [1]

This will assign the tag with the id 1 to the post. We can use this concept when we are creating a many to many checkbox. Let's take a look at the form

# app/views/posts/_form.html.erb<%= form_for @post do |f| %>  # ...  <div class='form-group'>    <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name do |t| %>      <div class='checkbox'>        <%= t.label do %>          <%= t.check_box + t.text %>        <% end %>      </div>    <% end %>  </div>  # ...<% end %>

Tying it all up in the Controller

If we submit this form we will see the {"tag_ids" => ["1", "2"]} we need to ensure that we support the parameter in our strong parameter in the controller

# app/controllers/posts_controller.rbclass PostsController < ApplicationController  # ...  private    def post_params    params.require(:post).permit(:title, :body, :tag_ids => [])  endend