Rails - 使用nil进行条件查询?

AnA*_*ice 7 ruby-on-rails ruby-on-rails-3

有什么想法这有什么不对吗?

    @contacts = current_user.contacts.where("fname = ? OR lname = ?", nil, nil)
Run Code Online (Sandbox Code Playgroud)

我想要所有联系人,其中fname或lname为空.

这是它在日志中显示的内容,不确定为什么它没有获取记录.

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

思考?

谢谢

Dyl*_*kow 28

如果你想要空(意味着一个空字符串,但实际上不是null),那么使用一个空字符串:

@contacts = current_user.contacts.where("fname = ? OR lname = ?", "", "")
Run Code Online (Sandbox Code Playgroud)

否则,如果您真的想要空值,则需要使用以下is null措辞:

@contacts = current_user.contacts.where("fname is null OR lname is null")
Run Code Online (Sandbox Code Playgroud)

您也可以使用:lname => nil,但该格式不能用于OR查询.注意不同之间"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
Run Code Online (Sandbox Code Playgroud)

  • `where("field is null")`在Postgres中正常工作. (2认同)