2

Assuming standard simple models as following:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
end

And my queries:

includes = {:posts => [:comments]}
person = Person.where(:id => 5).includes(includes)

Is there some way I can fetch comments from posts in batches? Because in some cases, a one user has thousands of posts, so the query it constructs to fetch the comments becomes very big and slow.

davegson
  • 8,205
  • 4
  • 51
  • 71
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • Are you lookings for [limit & offset](http://guides.rubyonrails.org/active_record_querying.html#limit-and-offset)? – davegson Apr 13 '15 at 11:14
  • 1
    Seems none of the above command answers the OP's question. Question is about limiting number of records of `comments` which lies under `includes`. – RAJ Apr 13 '15 at 11:21

1 Answers1

1

You can solve this if you fetch the comments in a second query.

# in your controller
@person = Person.where(id: 5).includes(:posts)

# in your view (haml)
- @person.posts.each do |post|
  = post.title
  - post.comments.find_each do |comment| # find_each is batched
    = comment.message

Perhaps not the most clean solution (each post requires an extra query, querying in the view...), but I am not aware of a way to fetch included items in batches.

zwippie
  • 15,050
  • 3
  • 39
  • 54