已加载关系的预加载关联



我想为已经加载的关系预加载关联,这样我就可以避免 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

我发现这仅适用于早期版本的 rails,使用 preload_associations 方法。我知道该方法仅供内部使用,但我想是否有办法为 rails 5+ 实现相同的效果?

Modern 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

最新更新