Rails 3 Limiting Included Objects

后端 未结 2 1644
礼貌的吻别
礼貌的吻别 2020-12-16 13:32

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

2条回答
  •  攒了一身酷
    2020-12-16 14:04

    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
    

提交回复
热议问题