Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload associations of already loaded relation

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+?

like image 836
rabusmar Avatar asked Jan 31 '26 03:01

rabusmar


1 Answers

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
like image 157
Chris Wu Avatar answered Feb 02 '26 21:02

Chris Wu