【问题标题】:Rails where.not, include record having nil attributeRails where.not,包括具有 nil 属性的记录
【发布时间】:2018-04-23 12:01:01
【问题描述】:

我有一个 Order 模型,其属性为 skip_reason。我想列出除fulllocked 之外的所有具有skip_reason 的订单。 我正在使用where.not,但它不会返回在skip_reason 列上具有nil 的订单。

我想出了以下条件,

> orders.pluck(:skip_reason)
=> ["locked", nil, nil, "unavailable", nil, nil, "locked", nil, nil, "full"]

> orders.where.not(skip_reason: ["full", "locked"]).pluck(:skip_reason)
=> ["unavailable"]

那么我如何列出那些在skip_reason 列中具有nil 值的订单?任何建议将不胜感激。

【问题讨论】:

  • 你能添加上面查询的 SQL 输出吗?
  • 由于@Ursus 指出您使用的是rails 4,因此您必须将原始SQL 用作orders.where("orders.skip_reason IS NULL OR orders.skip_reason NOT IN ('full','locked')")。 Rails 5 确实提供了or,它看起来像orders.where.not(skip_reason: ["full", "locked"]).or(orders.where(skip_reason: nil))

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


【解决方案1】:

在 rails 4 中尝试过,它似乎有效。这对你好吗?否则我认为你应该为 where 子句使用原始 SQL

orders.where(skip_reason: [nil, "unavailable"])

【讨论】:

  • 谢谢,但在这些情况下我可能还有其他数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
相关资源
最近更新 更多