'Where with OR condition for the same column in Rails

I'm trying to retrieve all records that have expired_at as nil and expired_at greater than the current time.

I've tried this:

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

But that is only returning me the records expired_at greater than DateTime.now. Why is the nil being neglected?



Solution 1:[1]

You can also take advantage of Rails or here, which will take care of having IS NULL instead of = NULL. I would also recommend using Time.current instead, which has better support for time zones.

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

Solution 2:[2]

I guess you can use the following syntax as well

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2