Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 973
lulalala Avatar asked Sep 24 '12 08:09

lulalala


2 Answers

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)
like image 161
lulalala Avatar answered Nov 07 '22 02:11

lulalala


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)
like image 41
Gabe Durazo Avatar answered Nov 07 '22 01:11

Gabe Durazo