【问题标题】:What's the difference between "left_joins" and "includes" in Rails 5?Rails 5 中的“left_joins”和“includes”有什么区别?
【发布时间】:2018-11-21 15:00:10
【问题描述】:

在 Rails 5 中,他们添加了 ActiveRecord 查询方法left_joinsleft_joinsincludes 有什么区别?我一直将includes 视为左连接。

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-5


    【解决方案1】:

    includes 默认在 2 个查询中加载关联数据,就像preload 一样。 但是通过额外的references 调用,它会从使用两个单独的查询切换到创建单个LEFT OUTER JOIN,例如left_joins

    参考:

    Preload, Eagerload, Includes and Joins

    Making sense of ActiveRecord joins, includes, preload, and eager_load

    【讨论】:

    • 如果您应用 where 子句,包含也将遵循 .eager_load 并在一个查询中加载记录。
    • @max 但默认情况下,您不能通过 includeswhere 子句中使用预先加载的表。您需要先在references 中指定它们
    • 我不确定你的意思,但你可以这样做Foo.includes(:bars).where(bars: { baz: 'woo' })。结果和使用 eager_load 一样。
    • @max 是的,但是如果您将示例更改为Foo.includes(:bars).where("bars.baz = 'woo'"),它将引发错误。在includes 文档中查看conditions 部分
    • @max 但我不知道hash 符号在没有references 调用的情况下也可以工作,所以谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2012-06-15
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多