Rails 3 限制包含的对象 [英] Rails 3 Limiting Included Objects
问题描述
例如,我有一个博客对象,该博客有很多帖子.我想做第一个博客对象的热切加载,并包括它的前 10 篇文章.目前我会做 @blogs = Blog.limit(4)
然后在视图中使用 @blogs.posts.limit(10)
.我很确定有一种更好的方法可以通过诸如 Blog.include(:posts).limit(:posts=>10)
之类的包含来做到这一点.是不能限制包含对象的数量,还是我在这里遗漏了一些基本的东西?
For example I have a blog object, and that blog has many posts. I want to do eager loading of say the first blog object and include say the first 10 posts of it. Currently I would do @blogs = Blog.limit(4)
and then in the view use @blogs.posts.limit(10)
. I am pretty sure there is a better way to do this via an include such as Blog.include(:posts).limit(:posts=>10)
. Is it just not possible to limit the number of included objects, or am I missing something basic here?
推荐答案
当急切加载多个记录的关联时,您似乎无法对 :has_many
应用限制.
Looks like you can't apply a limit to :has_many
when eager loading associations for multiple records.
示例:
class Blog < ActiveRecord::Base
has_many :posts, :limit => 5
end
class Post < ActiveRecord::Base
belongs_to :blog
end
这适用于限制单个博客的帖子数量:
This works fine for limiting the number of posts for a single blog:
ruby-1.9.2-p290 :010 > Blog.first.posts
Blog Load (0.5ms) SELECT `blogs`.* FROM `blogs` LIMIT 1
Post Load (0.6ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`blog_id` = 1 LIMIT 5
但是,如果您尝试加载所有博客并急切地加载帖子:
However, if you try to load all blogs and eager load the posts with them:
ruby-1.9.2-p290 :011 > Blog.includes(:posts)
Blog Load (0.5ms) SELECT `blogs`.* FROM `blogs`
Post Load (1.1ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`blog_id` IN (1, 2)
请注意,第二个查询没有限制,也不可能存在 - 它会将所有博客中返回的帖子数量限制为 5,这根本不是您想要的.
Note that there's no limit on the second query, and there couldn't be - it would limit the number of posts returned to 5 across all blogs, which is not at all what you want.
查看 Rails 文档 证实了这一点.你总是会在你弄清楚它们的那一刻找到这些东西:)
A look at the Rails docs confirms this. You always find these things the minute you've figured them out :)
如果你用指定的 :limit 选项急切加载关联,它将被忽略,返回所有关联的对象
If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects
这篇关于Rails 3 限制包含的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!