我想我需要类似于 Rails 急切加载的查询的东西,但我无法找到解决方案。
为简单起见,假设永远不会超过 30 个 Person
s 在系统中(所以 Person.all
是一个小数据集),但每个人将有超过 2000 条评论(所以 Person.include(:comments)
将是一个大数据集)。
家长会
class Person < ActiveRecord::Base
has_many :comments
end
child 协会
class Comment < ActiveRecord::Base
belongs_to :person
end
我需要查询
Person
的列表s 并包括他们的comments
,但我只需要其中的 5 个。我想做这样的事情:
有限的家长协会
class Person < ActiveRecord::Base
has_many :comments
has_many :sample_of_comments, \
:class_name => 'Comment', :limit => 5
end
Controller
class PersonController < ApplicationController
def index
@persons = Person.include(:sample_of_comments)
end
end
不幸的是,this article声明:“如果您急切地加载具有指定 :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
的钩子(Hook)关于ruby-on-rails - Rails 急切负载和限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9808674/