来自Rails 文档 http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Eager+loading+of+associations
如果您急切加载具有指定 :limit 选项的关联,它将被忽略,返回所有关联的对象
因此给出以下模型定义
class Category < ActiveRecord::Base
has_many :posts
has_many :included_posts, -> { limit 10 }, class_name: "Post"
end
Calling Category.find(1).included_posts
将按预期工作并在查询中应用 10 的限制。但是,如果你尝试这样做Category.includes(:included_posts).all
the limit
选项将被忽略。如果您查看一下急切加载生成的 SQL,您就会明白为什么会出现这种情况
Category.includes(:posts).all
Category Load (0.2ms) SELECT "categories".* FROM "categories"
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."category_id" IN (1, 2, 3)
如果您添加了LIMIT
posts 查询的子句,它将返回一个total共 10 个帖子和not如您所料,每个类别有 10 个帖子。
回到你的问题,我会急切地加载所有帖子,然后使用限制加载的集合first(10)
categories = Category.includes(:posts).all
categories.first.posts.first(10)
尽管您将更多模型加载到内存中,但这必然会提高性能,因为您只对数据库进行了 2 次调用,而调用次数为 n+1 次。干杯。