问题描述
我正在努力寻找ActiveRecord对象的include()和preload()的比较。谁能解释这个区别?
I'm struggling to find a comparison of includes() and preload() for ActiveRecord objects. Can anyone explain the difference ?
推荐答案
Rails有两种避免n + 1问题的方法。一种是创建一个基于大联接的查询以引入您的关联,另一种涉及为每个关联进行一个单独的查询。
Rails has 2 ways of avoiding the n+1 problem. One involves creating a big join based query to pull in your associations, the other involves making a separate query per association.
当您执行 includes
rails决定为您使用哪种策略。除非它认为您在条件或顺序中使用了关联中的列,否则它默认为单独的查询方法(预加载)。由于那仅适用于联接方法,因此它使用了该方法。
When you do includes
rails decides which strategy to use for you. It defaults to the separate query approach (preloading) unless it thinks you are using the columns from the associations in you conditions or order. Since that only works with the joins approach it uses that instead.
Rails的启发式方法有时会出错,或者您可能有特定的原因偏爱一种方法。 preload
(及其伴随方法 eager_load
)允许您指定要使用的策略。
Rails' heuristics sometimes get it wrong or you may have a specific reason for preferring one approach over the other. preload
( and its companion method eager_load
) allow you to specify which strategy you want rails to use.
这篇关于ActiveRecord查询中的“ includes”和“ preload”有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!