【问题标题】:Rails how to Query on Multiple JoinsRails 如何查询多个连接
【发布时间】:2020-04-04 03:13:45
【问题描述】:

我有三个表ContactNon Medical NeedsMedical Needs。联系 has_many 非医疗和医疗需求。

需求有一个fulfilled 布尔列,用于标记需求已完成。我需要查询所有未满足医疗或非医疗需求的联系人。

我尝试使用 or 关系进行查询,但它只返回需求的交集。这是我提出的查询

Contact.joins(:non_medical_reqs, :medicaL_reqs)
       .where(non_medical_reqs: {fullfilled: nil})
       .or(Contact.joins(:non_medical_reqs, :medicaL_reqs)
       .where(medical_reqs: {fullfilled: nil}))

编辑 我正在使用带有 Rails 6 的 Postgresql

【问题讨论】:

  • Protip - 不要将整个程序写在一行中。
  • 听起来你想要的是使用子查询或拥有。知道哪个数据库并拥有mce 会有所帮助。

标签: sql ruby-on-rails activerecord


【解决方案1】:

这可能有效。我已经在一个项目中尝试过类似的关系,它似乎有效。对于or,我只能让它与where 子句的结构略有不同。

Contact.left_joins(:non_medical_reqs, :medicaL_reqs).where('non_medical_reqs.fullfilled = ?', nil).or(Contact.left_joins(:non_medical_reqs, :medicaL_reqs).where('medical_reqs.fullfilled = ?', nil}))

为了进行健全性检查,我会提取以下查询并比较结果:

Contact.left_joins(:non_medical_reqs).where('non_medical_reqs.fullfilled = ?', nil)

Contact.left_joins(:medicaL_reqs).where('medical_reqs.fullfilled = ?', nil})

并确保这两个集合等于第一个查询的结果。

【讨论】:

  • 你可以写成where(medical_reqs: { fullfilled: nil })
  • @max 在我的答案末尾显示的两个单一查询中,但如果我在答案中使用or 版本中的格式,我会得到ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:references]。我在 Rails 5.1 上。
  • 已知问题:github.com/rails/rails/issues/24055。它可能与我的应用程序具有默认范围有关。但是除了:references 之外,还有其他原因。
  • 实际上我在这个应用程序中没有任何默认范围。所以不知道为什么它不喜欢那种形式。
  • 你有medicaL_reqs吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
相关资源
最近更新 更多