中間テーブルがある多対多のモデルをincludes
を行い、JSONでまとめて表示させたいのですが、うまくいかずエラーとなってしまいます。
原因がよくわかりません。
ご回答いただけば嬉しいです。。。!
Association named 'article_tag' was not found on Article; perhaps you misspelled it? render json: article.to_json(include: :tags)
モデルの関係性は以下の通りです。
article
多対多 article_tag
多対多 tag
JSONの出力イメージ
json
1[{ 2"id":1, 3"name":"食べ物", 4"smallspace_id":null, 5"created_at":"2019-04-11T16:27:55.000Z", 6"updated_at":"2019-04-11T16:27:55.000Z", 7"smallspaces":[{ 8 "id":1, 9 "name":"インド", 10 "space_id":1, 11 "created_at":"2019-04-11T16:27:55.000Z", 12 "updated_at":"2019-04-11T16:27:55.000Z" 13}, 14{"id":2,"name":"夕飯","space_id":1,"created_at":"2019-04-11T16:27:55.000Z","updated_at":"2019-04-11T16:27:55.000Z"} 15]}
ソースコード
Articleコントローラ
ruby
1class Api::V1::ArticleController < ApplicationController 2 def index 3 article = Article.all.includes(article_tags: :tags) 4 5 render json: article.to_json(include: :tags) 6 end 7end
Articleモデル
ruby
1class Article < ApplicationRecord 2 has_many :article_tags 3 has_many :tags, through: :article_tags 4end 5
ArticleTagモデル(中間テーブル)
ruby
1class ArticleTag < ApplicationRecord 2 belongs_to :article 3 belongs_to :tag 4end 5
Tagモデル
ruby
1class Tag < ApplicationRecord 2 has_many :article_tags 3 has_many :articles, through: :article_tags 4end 5
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/15 16:53