I'd like to preload associations for an already loaded relation, so I can avoid the N+1 problem. The thing is that I cannot rewrite the original query because I want to preload associations only on certain cases, something like this:
results = SomeModel.where(some_condition).load
# do some stuff with the results
if some_condition
preload_associations(results, [:some_association, :another_association])
# do some stuff with the results and preloaded associations
end
I've only found this possible for early versions of rails, using the method preload_associations. I know the method was intended for internal use only, but I'd like if there is a way to achieve the same for rails 5+?
Modern rails uses a helper class to handle that: https://www.rubydoc.info/docs/rails/4.1.7/ActiveRecord/Associations/Preloader
In your example I believe you'd do something like:
results = SomeModel.where(some_condition).load
# do some stuff with the results
if some_condition
ActiveRecord::Associations::Preloader.new.preload(results, [:some_association, :another_association])
# do some stuff with the results and preloaded associations
end
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