以下のように中間テーブルを通して、Blog
からTag
のtitle
カラムの値を行いたいです。
Blog
多対多 blog_tags(中間テーブル)
多対多 Tag
Blogテーブル
id | title |
---|---|
1 | ラーメンの記事 |
2 | ガジェットの記事 |
blog_tags(中間テーブル)
id | blog_id | tag_id |
---|---|---|
1 | 1 | 2 |
2 | 2 | 1 |
Tagテーブル
id | title |
---|---|
1 | 食べ物 |
2 | ガジェット |
RailsはAPIとしてJSON出力するため、コントローラのrender
時点で、「食べ物」「ガジェット」といったtitle
カラムを取得したいのですが、
書き方が調べてもよくわからず、どのように行えばいいのかわかりません。
ご教授いただければ助かります。
blog_controller
ruby
1class BlogController < ApplicationController 2 def index 3 blog = Blog.includes([blog_tags: :tag]) 4 5 render json: blog 6 end 7end
各モデルのソースコード
ブログモデル blog.rb
ruby
1class Blog < ApplicationRecord 2 has_many :tags, through: :blog_tags 3 has_many :blog_tags 4end 5
中間モデル blog_tags.rb
ruby
1class BlogTag < ApplicationRecord 2 belongs_to :blog 3 belongs_to :tag 4end
タグモデル tag.rb
ruby
1class Tag < ApplicationRecord 2 has_many :blogs, through: :blog_tags 3 has_many :blog_tags 4end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/19 18:03