has many through 多多のアソシエーションを使ってcollection_check_boxes でカテゴリーのタグ付けを実装する。 ほぼビュー周り。


「Rails4のhas_many throughで多対多のリレーションを実装する」http://qiita.com/samurairunner/items/cbd91bb9e3f8b0433b99
の次回がなかった(からかなり困った)のでビュー周りも紹介する。

前半は上の記事と同じ


参考 http://qiita.com/samurairunner/items/cbd91bb9e3f8b0433b99

イメージ画像を作るのは面倒だったので拝借。
これのprojectsがarticlesにprojects_categoriesがarticle_categoriesになったバージョンと考えればいい。

model

category model

app/models/category.rb
class Category < ActiveRecord::Base
  has_many :article_categories
  has_many :articles, through: :article_categories
end

article model

app/models/article.rb
class Category < ActiveRecord::Base
  has_many :article_categories
  has_many :categories, through: :article_categories
end

article_categories model

app/models/article_categories.rb
class ArticleCategory < ActiveRecord::Base
  belongs_to :article
  belongs_to :category
end

ほぼ上の記事と一緒

ここからがいよいよ本番ビュー周り

article controller

app/controllers/articles_controller.rb
def create
    @article = Article.new(article_params)
    @article.user = current_user
    if @article.save
      flash[:success] = "as you like"
      redirect_to article_path(@article)
    else
      render 'new'
    end
 end

......................................................................

private
   #ここがポイント category は collection_check_boxesのチェックボックスで複数選択の入力で値を渡す場合arrayで渡ってくるのでcategory_ids: []で受け取ると上手くいった
    def article_params
      params.require(:article).permit(:any, category_ids: [])
    end


そして肝心のビューは

article new

app/views/articles/new.index.erb
<%= f.collection_check_boxes :category_ids, Category.all, :id, :name do |ccb| %>
 <% cb.label(class: "any")
{ccb.check_box(class: "any") + ccb.text} %>
 <% end %>

見たこと無い形だったのでクラスをつけるのに苦労した。

これで指定したタグをつけるタイプのタグ付けを実装できる。

参考 

collection_cheach_box

model周り

初心者、初投稿なので心配。
記法とかのアドバイスがあったらください。