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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With