Rails渴望加载和限制

Cha*_*d M 6 ruby-on-rails limit eager-loading

我认为我需要一些类似于rails eager加载查询的东西,但有限制,但我找不到解决方案.

为简单起见,我们假设系统中永远不会超过30 Person秒(因此Person.all是一个小数据集),但每个人将有超过2000条评论(因此Person.include(:comments)将是一个大型数据集).

家长协会

class Person < ActiveRecord::Base
  has_many :comments
end
Run Code Online (Sandbox Code Playgroud)

儿童协会

class Comment < ActiveRecord::Base
  belongs_to :person
end
Run Code Online (Sandbox Code Playgroud)

我需要查询Persons 列表并包含它们comments,但我只需要其中的5个.

我想做这样的事情:

有限的家长协会

class Person < ActiveRecord::Base
  has_many :comments
  has_many :sample_of_comments, \
    :class_name => 'Comment', :limit => 5
end
Run Code Online (Sandbox Code Playgroud)

调节器

class PersonController < ApplicationController
  def index
    @persons = Person.include(:sample_of_comments)
  end
end
Run Code Online (Sandbox Code Playgroud)

遗憾的是,本文指出:"如果您急于加载具有指定:limit选项的关联,它将被忽略,返回所有关联的对象"

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

cho*_*eat 0

不管“那篇文章”说什么,问题在于 SQL,在这种情况下,您无法纯粹通过使用标准来缩小第二个 sql 查询(急切加载)的范围。LIMIT

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

  1. 将您的第二个关联更改为Person has_many :sample_of_comments, conditions: { is_sample: true }
  2. 向表中添加一is_samplecomments
  3. 添加一个Comment#before_create分配的钩子is_sample = person.sample_of_comments.count < 5