Conditional query with zero?

Any ideas what is wrong with this?

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

I need all the contacts, where either the name or the name is empty.

This is what he shows in magazines, not sure why he is not receiving entries.

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

Thoughts?

thanks

+7
source share
1 answer

If you want an empty string (which means an empty string, but not the actual null value), use an empty string:

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

Otherwise, if you really need null values, you need to use the is null wording:

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

Instead, you can use :lname => nil , but this format cannot be used for OR queries. Note the difference between "lname = ?", nil :lname => nil and :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 
+28
source

All Articles