Reputation: 442
If I have an instance of ActiveRecord model and I know that I will use a lot its association, I preload them using preload or include method on an ActiveRecord::Relation : Model.where(...).preload(:associated_model).first
.
But is there a way to preload the associations of a model, when the model is already instantiated, without reloading it ?
Let's imagine I load my model :
model_instance = Model.find(x)
then, I would expect something like :
model_instance.load(:associated_model)
With a load method that would do a query to find the associated_model and preload it, but without reloading the model_instance.
Upvotes: 9
Views: 3188
Reputation: 36144
This will do it for an array of models with a single query (for a single one use [my_model]
in place of my_models
):
ActiveRecord::Associations::Preloader.new(records: my_models,
associations: [:my_association]).call
Note that preloads are cached, so calling the preload again will not refresh it. There are methods for clearing preloads so you can preload them again (or let them load on use). For associated collections there's the .reset
method (e.g. my_model.my_associations.reset
). And for has_one
/belongs_to
associations, Rails 7.1 will have my_model.reset_my_association
. See 09. Allow resetting singular associations.
Upvotes: 3
Reputation: 1534
using model_instance.associated_model
will only load the association for the first time.
If we open rails console and try it there, we'll see that it has queried the database only first time and after that all the calls to associated model didn't load it from database.
Upvotes: 1