How to use Eager loading(includes) with find_in_batches rails

Viewed 596

I have a large number of rows in the users table for which I need to apply eager loading to load user's comments.

User.includes(:comments)

Since the user set is too large it consumes a lot of memory while adding eager loading.

So after going through a couple of solutions I ended with below

User.select(:id).find_in_batches do |user|
  users = User.where(id: user_id).includes(:comments)
end

Is there a better way to perform eager loading with find_in_batches?

1 Answers

You could use find_in_batches like this:

User.where(id: user_ids).includes(:comments).find_in_batches do |users|
  users.each do |user|
    user.comment
  end
end

It will eager_loading comments by each batch automatically.

Related