2011-05-06 140 views
7

任何想法這是什麼問題?Rails - 使用nil進行條件查詢?

@contacts = current_user.contacts.where("fname = ? OR lname = ?", nil, nil) 

我希望fname或lname爲空的所有聯繫人。

這是什麼它顯示在日誌中,不知道爲什麼它沒有得到記錄。

Contact Load (0.6ms) SELECT "contacts".* FROM "contacts" WHERE ("contacts".user_id = 2) AND (fname = NULL OR lname = NULL) 

想法?

感謝

回答

28

如果你想空(意思是一個空字符串,但實際上沒有空),然後用一個空字符串:

@contacts = current_user.contacts.where("fname = ? OR lname = ?", "", "") 

否則,如果你真正想要的空值,則需要使用is null措辭:

@contacts = current_user.contacts.where("fname is null OR lname is null") 

您還可以使用:lname => nil代替,但格式不能用於或查詢。注意:"lname = ?", nil:lname => nil之間的不同:

@contacts = Contact.where("lname = ?", nil).to_sql 
# => SELECT "contacts".* FROM "contacts" WHERE (lname = NULL) 

@contacts = Contact.where(:lname => nil).to_sql 
# => SELECT "contacts".* FROM "contacts" WHERE "contacts"."lname" IS NULL 
+2

'那裏( 「字段爲空」)'在Postgres的正常工作。 – Abel 2015-10-30 17:30:43