【发布时间】:2020-07-16 08:31:36
【问题描述】:
似乎includes(:associations).references(:associations) 和eager_load(:associations) 在Rails 5 中执行完全相同 SQL (LEFT OUTER JOIN)。那么我什么时候需要使用includes(:associations).references(:associations) 语法?
例如,
Parent.includes(:children1, :children2).references(:children1).where('(some conditions of children1)')
可以转换成
Parent.eager_load(:children1).preload(:children2).where('(some conditions of children1)')
我认为后者(使用eager_load 和preload 进行查询)更简单,看起来更好。
更新
我在我的环境中发现了一个奇怪的行为 (rails 5.2.4.3)。
即使我includes 几个关联并且references 仅其中一个,所有我包含的关联都是LEFT OUTER JOINed。
例如,
Parent.includes(:c1, :c2, :c3).references(:c1).to_sql
执行LEFT OUTER JOINs 所有c1、c2、c3 的SQL。
我以为它只加入 c1。
【问题讨论】:
-
主要区别在于
.includes尝试使用一组复杂的启发式方法来判断它是否要在一个查询或两个查询中加载记录。无论如何,使用.references是使其委托给.eager_load的条件之一,这就是它加入:c1, :c2, :c3的原因。如果您事先知道您将使用关联.eager_load以直接的方式完成这项工作。 -
那么我什么时候需要使用
includes(:associations).references(:associations)语法呢?好吧,可能永远不会使用.eager_load。
标签: ruby-on-rails activerecord ruby-on-rails-5