Rails 3的限制包含的对象 [英] Rails 3 Limiting Included Objects

查看:139
本文介绍了Rails 3的限制包含的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个博客对象,该博客有很多文章。我想要做的预先加载的说,第一个博客对象,包括说出的第10个职位吧。目前,我会做 @blogs = Blog.limit(4),然后在视图中使用 @ blogs.posts.limit(10)。我是pretty的肯定有一个更好的方式来做到这一点通过包括诸如 Blog.include(:职位).limit(:帖子=> 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 :)

如果你渴望负载与指定的关联:限制选项,它   会被忽略,返回所有相关联的对象

If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects

这篇关于Rails 3的限制包含的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆