iibmha
Last Updated: February 25, 2016
·
1.944K
· mschae
02176ee838cb662af64ea4b2b90eeb32

Prefetch associations for existing model instances

Most of us will know and use this frequently:

Model.includes(:another_model, :yet_another_model, some_model_with: :associated_models).all

But what if (e.g. out of a cache or a complicated join query) you already have model instances and now would want to prefetch its corresponding associations?

There is an easy way to do this:

ActiveRecord::Associations::Preloader.new(objects, [:another_model, :yet_another_model, some_model_with: :associated_models]).run

This will "cache" the associated objects within the objects. Important here is that it will use one query per model type to prefetch all the objects.

So this:

objects.each{|o| o.another_model.do_something }

will not result in one query per iteration.

Say Thanks
Respond