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.
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.
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