Railswhere条件取关联记录时N+1查询问题

Rails N + 1 query problem when fetching associated records with where condition

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

UserPost => user_id, post_id, Post, Comment

所以,如果我尝试使用以下查询获取所有 user_posts 并在 comments table 上执行 where 然后它会触发对 comments table

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

您可以做的是向您的模型添加另一个 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'

...并在您的查询中预先加载,这将预先加载两种类型的评论。这样必然会多出一个query,但不是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