Railsで多対多の関連をチェックボックスで設定

Railsで多対多の関連をチェックボックスで設定する時のメモ

Model

$ rails g model post name:string
$ rails g model tag name:string
$ rails g model post_tag post:references tag:references

post.rb

class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, through: :post_tags
end

tag.rb

class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, through: :post_tags
end

post_tag.rb

class PostTag < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag
end

View

= collection_check_boxes(:post, :tag_ids, Tag.all, :id, :name) do |t|
  = t.label(class: "checkbox-inline") { t.check_box + t.text }

Controller

def post_params
  params.require(:post).permit(:name, {:tag_ids => []})
end

参考