lulalala
lulalala

Reputation: 17981

How to eager load association for an array of model records

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.

Upvotes: 20

Views: 6305

Answers (2)

lulalala
lulalala

Reputation: 17981

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)

Upvotes: 36

Gabe Durazo
Gabe Durazo

Reputation: 1809

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)

Upvotes: 2

Related Questions