首页 > 解决方案 > Rails N + 1查询问题时获取与where条件关联的记录

问题描述

我有下表结构。这只是一个例子

UserPost => user_id, post_id, Post, Comment

因此,如果我尝试user_posts使用以下查询获取所有内容并在comments表上执行位置,那么它会触发对该comments表的查询

user_posts = UserPost.includes(post: :comments)
user_posts.each do |up|
  post = up.post # No Query
  comments = up.comments # No query
  comments_with_condition = up.comments.where(visibility: true).order(position: :asc).first.data # Fires query for .where and .order as well.
end

那么,这是预期的行为还是我做错了什么?

如何防止每个人的查询user_post

标签: ruby-on-railsruby-on-rails-6.1

解决方案


您可以做has_many的是使用您想要的过滤器将另一个添加到您的模型中。

# You can name this anything you want but a descriptive name helps
has_many :special_comments, -> { where(visibility: true).order(..) }, class_name: 'Comment'

...并在您的查询中急切加载,这将急切加载两种类型的评论。这不可避免地会导致一个额外的查询,但它不是N+1。

user_post = UserPost.includes(post: [:comments, :special_comments])

user_posts.each do |user_post|
  post = user_post.post
  comments = user_post.comments
  comments_with_condition = user_post.special_comments
end

推荐阅读