Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload associations of an already loaded model

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.

like image 948
Jean-Théo Avatar asked Nov 10 '22 06:11

Jean-Théo


1 Answers

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.

like image 187
Kinaan Khan Sherwani Avatar answered Nov 14 '22 21:11

Kinaan Khan Sherwani