Rails急切的负载和限制 [英] Rails Eager Load and Limit

查看:70
本文介绍了Rails急切的负载和限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我需要类似于Rails渴望加载的查询,但有一个限制,但是我很难找到解决方案.

I think I need something akin to a rails eager loaded query with a limit on it but I am having trouble finding a solution for that.

为简单起见,让我们说系统中的Person永远不会超过30个(因此Person.all是一个小的数据集),但每个人最多可以有2000条注释(因此将会是一个大数据集.

For the sake of simplicity, let us say that there will never be more than 30 Persons in the system (so Person.all is a small dataset) but each person will have upwards of 2000 comments (so Person.include(:comments) would be a large data set).

父母协会

class Person < ActiveRecord::Base
  has_many :comments
end

儿童协会

class Comment < ActiveRecord::Base
  belongs_to :person
end

我需要查询Person的列表并包括它们的comments,但是我只需要5个即可.

I need to query for a list of Persons and include their comments, but I only need 5 of them.

我想做这样的事情:

有限的家长协会

class Person < ActiveRecord::Base
  has_many :comments
  has_many :sample_of_comments, \
    :class_name => 'Comment', :limit => 5
end

控制器

class PersonController < ApplicationController
  def index
    @persons = Person.include(:sample_of_comments)
  end
end

不幸的是,本文指出:如果您渴望加载与指定的:limit选项关联,它将被忽略,并返回所有关联的对象"

Unfortunately, this article states: "If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects"

有什么好的方法吗?还是我注定要在渴望加载1000个不需要的ActiveRecord对象和N + 1查询之间进行选择?另请注意,这是一个简化的示例.在现实世界中,在相同的index动作中,与comments相同的问题中,我还会与Person有其他关联. (照片,文章等).

Is there any good way around this? Or am I doomed to chose between eager loading 1000s of unneeded ActiveRecord objects and an N+1 query? Also note that this is a simplified example. In the real world, I will have other associations with Person, in the same index action with the same issue as comments. (photos, articles, etc).

推荐答案

无论那篇文章"说了什么,问题出在SQL中,您无法以想要的方式缩小第二个sql查询(急于加载)的范围在这种情况下,纯粹是使用标准的LIMIT

Regardless of what "that article" said, the issue is in SQL you can't narrow down the second sql query (of eager loading) the way you want in this scenario, purely by using a standard LIMIT

但是,您可以添加新列并改为执行WHERE子句

You can, however, add a new column and perform a WHERE clause instead

  1. 将您的第二个关联更改为Person has_many :sample_of_comments, conditions: { is_sample: true }
  2. comments表中添加is_sample
  3. 添加一个分配is_sample = person.sample_of_comments.count < 5
  4. Comment#before_create钩子
  1. Change your second association to Person has_many :sample_of_comments, conditions: { is_sample: true }
  2. Add a is_sample column to comments table
  3. Add a Comment#before_create hook that assigns is_sample = person.sample_of_comments.count < 5

这篇关于Rails急切的负载和限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆