【问题标题】:Rails N + 1 query problem when fetching associated records with where conditionRails N + 1查询问题时获取与where条件关联的记录
【发布时间】:2021-04-17 01:53:16
【问题描述】:

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

UserPost => user_id, post_id, Post, Comment

所以,如果我尝试使用以下查询获取所有 user_posts 并在 comments 表上执行 where 则它会触发对 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-rails ruby-on-rails-6.1


    【解决方案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'
    

    ...并在您的查询中急切加载它,这将急切加载两种类型的 cmets。这将不可避免地导致一个额外的查询,但它不是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多