我是从概念上知道的。
我想知道什么时候使用哪个 API。我搜索但没有找到确切答案。
最佳答案
includes
选择是使用preload
还是eager_load
。如果您对 includes
做出的决定不满意,您必须使用 eager_load
或 preload
来自 https://engineering.gusto.com/a-visual-guide-to-using-includes-in-rails/ :
:includes 什么时候使用:preload?
在大多数情况下 :includes 将默认使用方法 :preload 将触发 2 个查询:
- 加载与领先模型相关的所有记录
- 根据关联模型或主导模型上的外键加载与主导模型关联的记录
:includes 什么时候使用 :eager_load?
:includes 将默认使用 :preload 除非您在后续子句中引用正在加载的关联,例如 :where 或 :order。以这种方式构建查询时,您还需要显式引用预先加载的模型。
Employee.includes(:forms).where('forms.kind = "health"').references(:forms)
关于ruby-on-rails - 什么时候使用 preload 或 eager_load 或 includes 更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69242991/