19

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.

lulalala
  • 17,572
  • 15
  • 110
  • 169

2 Answers2

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)
NobodysNightmare
  • 2,992
  • 2
  • 22
  • 33
lulalala
  • 17,572
  • 15
  • 110
  • 169
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)
Gabe Durazo
  • 1,789
  • 2
  • 19
  • 27