Rails渴望加载和限制

时间:2012-03-21 16:20:38

标签: ruby-on-rails limit eager-loading

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

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

家长协会

class Person < ActiveRecord::Base
  has_many :comments
end

儿童协会

class Comment < ActiveRecord::Base
  belongs_to :person
end

我需要查询Person的列表并包含他们的comments,但我只需要其中的5个。

我想做这样的事情:

有限家长协会

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

不幸的是,this article表示:“如果您急于加载具有指定:limit选项的关联,它将被忽略,返回所有关联对象”

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

1 个答案:

答案 0 :(得分:0)

无论“那篇文章”说什么,问题都在SQL中,你无法在这种情况下以你想要的方式缩小第二个sql查询(急切加载),纯粹是通过使用标准LIMIT

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

  1. 将您的第二个关联更改为Person has_many :sample_of_comments, conditions: { is_sample: true }
  2. is_sample列添加到comments表格
  3. 添加指定Comment#before_create
  4. is_sample = person.sample_of_comments.count < 5挂钩
相关问题