class CommentsController < ApplicationController
def users_comments
posts = Post.all
comments = posts.map(&:comments).flatten
@user_comments = comments.select do |comment|
comment.author.username == params[:username]
end
end
end
答案 0 :(得分:3)
尝试:
通过将方法中的第一行更改为:
,可以避免这一切posts = Post.includes(comments: [:user]).all
像
class CommentsController < ApplicationController
def users_comments
posts = Post.includes(comments: [:user]).all
comments = posts.map(&:comments).flatten
@user_comments = comments.select do |comment|
comment.author.username == params[:username]
end
end
答案 1 :(得分:0)
代码中缺少end
的{{1}},您还需要包含do
和comments
关联以避免n + 1个查询。
author
所以代码看起来像
posts = Post.includes(comments: :author)