アソシエーションしている子モデルから親モデルのデータを取得する際、N+1が発生します。
前提
・User
・Article
・Comment
以上のモデルがあります。
UserとArticleは1対多の関係であり、ArticleとCommentも1対多です。
そして、モデルでの関連付けは以下のようになっています。
ruby
1#### User 2class User < ApplicationRecord 3 has_many :articles 4 has_many :comments 5end
ruby
1#### Article 2class Article < ApplicationRecord 3 belongs_to :user 4 has_many :comments 5end
ruby
1#### Comment 2class Comment < ApplicationRecord 3 belongs_to :user 4 belongs_to :comment 5end
やりたいこと
ruby
1@article = Article.find_by(article_id: [article_id]) 2@comment = @article.comments
上記で取得した@commentをview側でループして表示するのですが、CommentのUserを表示しようとすると"N+1"が発生します。
slim
1- @comment.each do |comment| 2 = comment.comment_detail 3 = comment.user.user_name ## ここで発生
includes等は使えませんよね?どう対処すればよいでしょうか?
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/26 13:18
2020/01/26 22:11