![](/img/trans.png)
[英]Ruby on Rails - "Add 'gem sqlite3'' to your Gemfile"
[英]Ruby on Rails - Bullet Gem. Add to your query: .includes([:author])
我有一个 N+1 查询问题,但我不明白如何解决这个问题。
我有一个用户模型、帖子模型和评论模型。
User has many posts
User has many comments
Post belongs to User
Post has many Comments
Comments belong to user
Comment belongs to post
在我的后控制器中,我有
def index
@posts = Post.includes(:author).where(author_id: params[:user_id])
end
def show
@post = Post.includes(:author).find(params[:id])
end
我从 Bullet Gem 收到这两个警告
user: espada
GET /users/2/posts/6
USE eager loading detected
Comment => [:author]
Add to your query: .includes([:author])
Call stack
user: espada
GET /users/2/posts/6
USE eager loading detected
Comment => [:post]
Add to your query: .includes([:post])
Call stack
我尝试在各种操作中添加这两个 .include,在过去 5 小时内尝试了很多事情......没有任何效果。 此时,我想了解在哪里添加这两个包含?
以及如何解释这一信息?
它在评论模型上显示错误
尝试这个
def index
@posts = Post.includes(:author, comments: %i[author post]).where(author_id: params[:user_id])
end
def show
@post = Post.includes(:author, comments: %i[author post]).find_by_id(params[:id])
end
您可能正在寻找对评论的依赖,而不是对帖子的依赖。 所以你必须像这样包含它。
Post.includes(:author, comments: [:author, :post]).find(params[:id])
感谢Larkin提到问题可能出在视图中,我去查看了我的 Post index 和 Post show view。
在我的帖子显示和索引视图中,我渲染了部分评论
<%= render partial: "shared/post/comment_card", locals: { post: @post, comments: @post.comments} %>
在我的评论卡中,我有一个删除按钮
<%= button_to "Delete Comment", user_post_comment_path(comment.author, comment.post, comment),
method: :delete, data: { confirm: "Are you sure?" } %>
当我收到每条评论的帖子时,这就是警告的来源。 我意识到,由于我是通过本地人在帖子中传递的,所以我可以将删除按钮写为
<%= button_to "Delete Comment", user_post_comment_path(comment.author, post, comment),
method: :delete, data: { confirm: "Are you sure?" } %>
这解决了这个错误。
然而,我也不得不改变我的表演动作,因为试图获得一个没有评论的帖子会引发警告,所以我把它写成
def show
@post = Post.includes(:author).find(params[:id])
@post = Post.includes(:author, comments: [:author]).find(params[:id]) if @post.comments.any?
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.