我想为已经加载的关系预加载关联,因此可以避免N + 1问题。问题是我无法重写原始查询,因为我只想在某些情况下预加载关联,例如:
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
我发现使用preload_associations方法仅对早期版本的rails可行。我知道该方法仅供内部使用,但我想知道是否有办法在Rails 5+上实现相同的效果?
答案 0 :(得分:1)
现代rails使用助手类来处理该问题:https://www.rubydoc.info/docs/rails/4.1.7/ActiveRecord/Associations/Preloader
在您的示例中,我相信您会做类似的事情:
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