2015-11-14 28 views
1

我試圖讓所有與到期日期(日期類型)是無優惠券:的Rails查詢無問題

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

但由於某些原因,上面的代碼不起作用。 然而,如果不是我做的:

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

它讓所有的零優惠券,我想它。我很困惑,爲什麼第一個不工作,但第二個工作。任何幫助,將不勝感激。

回答

2

NULLNOT NULL的SQL查詢如下:

expirationDate IS NULLexpirationDate IS NOT NULL

它不等於 「=」 號的工作。你不能在SQL做的 expirationDate = NULL

你可以嘗試這樣也

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

你可以看看這個答案狀況https://stackoverflow.com/a/4252615/343679

+0

啊啊,謝謝。沒有意識到這一點。 – ben3019201

3

使用null對其他替代品exampel。

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

SQL輸出:

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

其他格式:

u = User.where(name: nil) 

SQL輸出:

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

你會發現SQL不同。詳細信息SQL is null and = null [duplicate]