Rails 3 Limiting Included Objects

谁都会走 提交于 2019-11-29 03:20:46

Looks like you can't apply a limit to :has_many when eager loading associations for multiple records.

Example:

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)

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.

EDIT:

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

You need to limit the number of posts in your blog model like this:

class Blog < ActiveRecord::Base
    has_many :included_posts, :class_name => 'Post', :limit => 10
    has_many :posts
end

So then you can do:

$ Blog.first.included_posts.count
=> 10
$ Blog.first.posts.count 
=> 999
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!