Rails渴望加载和限制
我认为我需要一些类似于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 'Comment', :limit => 5 end
调节器
class PersonController < ApplicationController def index @persons = Person.include(:sample_of_comments) end end
不幸的是, 这篇文章指出:“如果你急于加载与指定的:limit选项的关联,它将被忽略,返回所有关联的对象”
这有什么好办法吗? 或者我注定要在急切加载1000个不需要的ActiveRecord对象和N + 1查询之间进行选择? 另请注意,这是一个简化的示例。 在现实世界中,我将与Person
有其他关联,在相同的index
操作中具有与comments
相同的问题。 (照片,文章等)。
无论“那篇文章”说什么,问题都出现在SQL中,你无法在这种情况下以你想要的方式缩小第二个sql查询(急切加载),纯粹是通过使用标准的LIMIT
但是,您可以添加新列并执行WHERE子句
- 将您的第二个关联更改为
Person has_many :sample_of_comments, conditions: { is_sample: true }
- 将一个
is_sample
列添加到comments
表 - 添加
Comment#before_create
挂钩,指定is_sample = person.sample_of_comments.count < 5