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?
Advertisement
Answer
Your current query checks that expired_at is equal to null (via = NULL) which will not evaluate to true. Instead, you want to query that the column is a null value by using IS NULL.
Therefore, the query can be tweaked to the following:
PriceRule.where("expired_at > ? OR expired_at IS NULL", DateTime.now)
Or, if you wish to keep your original argument structure, you can pass nil as before:
PriceRule.where("expired_at > ? OR expired_at IS ?", DateTime.now, nil)