Rails 中同一列的 OR 条件

Where with OR condition for the same column in Rails

我正在尝试检索所有 expired_at 为 nil 且 expired_at 大于当前时间的记录。

我试过这个:

PriceRule.where("expired_at > ? OR expired_at = ?", DateTime.now, nil)

但那只是返回给我 expired_at 大于 DateTime.now 的记录。为什么 nil 被忽略了?

您当前的查询检查 expired_at 是否等于 null(通过 = NULL),这不会计算为 true。相反,您想使用 IS NULL.

查询该列是否为空值

因此,可以将查询调整为以下内容:

PriceRule.where("expired_at > ? OR expired_at IS NULL", DateTime.now)

或者,如果您希望保留原始参数结构,您可以像以前一样传递 nil

PriceRule.where("expired_at > ? OR expired_at IS ?", DateTime.now, nil)

您也可以利用 Rails or here, which will take care of having IS NULL instead of = NULL. I would also recommend using Time.current,它对时区的支持更好。

PriceRule
  .where(expired_at: Time.current..)
  .or(PriceRule.where(expired_at: nil))

我猜你也可以使用下面的语法

PriceRule
.where(expired_at: DateTime.now..)
.or(PriceRule.where(expired_at: nil))