我想为已经加载的关系预加载关联,因此可以避免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+上实现相同的效果?
现代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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句