20

I have an array of Rails model records. Is it possible to eager load an association for all these records in one go (query)?

Sometimes I only have an array instead of an AR::Scope. And sometimes I want to dynamically choose what to eager load later.

2 Answers 2

36

In Rails 3, one can use preloader to eager-load associations on existing records.

ActiveRecord::Associations::Preloader.new(posts,:comments).run()

In Rails 4.1+ the call signature changed slightly:

ActiveRecord::Associations::Preloader.new.preload(posts,:comments)
4
  • 2
    This is deprecated in Rails 4.2
    – Leo Correa
    Nov 17, 2015 at 18:21
  • 3
    Rails4: ActiveRecord::Associations::Preloader.new.preload(posts, :catalogs)
    – Hooopo
    Nov 24, 2015 at 18:08
  • @LeoCorrea I don't see it's deprecated in Rails 4.2. Can you give some hint where I can find the deprecation note? Thanks.
    – Anh Nguyen
    Apr 15, 2016 at 20:53
  • 2
    ActiveRecord::Associations::Preloader.new.preload(posts,:comments) still works in Rails 5!
    – Finn
    Oct 21, 2018 at 23:32
1

Well, you could refind those objects. Map ':id' over your array, to get the records' ids, and then refind, this time eager-loading.

If your array of, say, Post model records is posts, then it'd be:

Post.find(posts.map &:id).includes(:blah)
1
  • 1
    My set is quite large so this reloading is too expensive. I was hoping for an API way.
    – lulalala
    Sep 25, 2012 at 1:33

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.