1

I'm trying to get all the coupons with an expirationDate(date type) that are nil:

  @coupons = @deal.coupons.all 
  @coupons = @coupons.where("expirationDate = ?", nil)

But for some reason the code above doesn't work. However, if instead I do:

@coupons = @deal.coupons.all
@coupons = @coupons.where(expirationDate: nil)

It gets all the nil coupons as I want it to. I'm confused as to why the first one doesn't work, but the second one does. Any help would be appreciated.

ben3019201
  • 391
  • 1
  • 4
  • 13

2 Answers2

3

for exampel.

User.where("name = ?",nil)

sql output :

SELECT "users".* FROM "users"  WHERE (name = NULL)

The other format:

u = User.where(name: nil)

sql output:

SELECT "users".* FROM "users"  WHERE "users"."name" IS NULL

You will find the sql different. Detail for SQL is null and = null [duplicate]

Community
  • 1
  • 1
kai
  • 310
  • 3
  • 14
2

The SQL query for NULL or NOT NULL is as following:

expirationDate IS NULL or expirationDate IS NOT NULL

It doesn't work with equal "=" sign. You can't do in SQL as expirationDate = NULL

You could try like this as well

@coupons = @coupons.where("expirationDate IS NULL")

You can take a look at this answer for other alternatives of using null in condition https://stackoverflow.com/a/4252615/343679

Community
  • 1
  • 1
Sharjeel
  • 15,588
  • 14
  • 58
  • 89