Question

I have a rails app with a Customer and a ShippingAddress model. It is implemented with a one-to-many relationship so that a ShippingAddress can have multiple customers.

I am successfully able to query across these two models and several others with an include statement, but as I tried to update the query to find all of the customers that does not have a shipping_address got 0 results, even though I am able to se from my DB-admin tool that I have multiple customers where the value of the shipping_address_id is nil.

These queries works, but does not give me customers without addresses:

Customer.includes(:orders, :shipping_address).where('customers.name LIKE ? or customers.mail LIKE ?', searchstring, searchstring)

Customer.where('customers.shipping_address_id = ?',2)

These attempts to adapt the above to give me customers without addreses doesn't:

Customer.includes(:orders, :shipping_address).where('shipping_address = ?', nil)

Customer.includes(:orders, :shipping_address).where('shipping_address = NULL')

# At the very least I should be able to get the right result by referencing the fk directly, but no?
Customer.where('customers.shipping_address_id = ?',nil)   

What am I missing here?

Était-ce utile?

La solution

The NULL value can be surprising until you get used to it. Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values.

You cannot compare null using equal to for this you must use IS NULL. So update your queries to

Customer.includes(:orders, :shipping_address).where('customers.shipping_address_id IS NULL')

Or rails way of doing this is

Customer.where(shipping_address_id: nil).includes(:orders, :shipping_address)

Autres conseils

You could also just do:

@customers_without_shipping_ids = Customer.where('shipping_address_id IS NULL').all

Please have a try with these queries

Customer.all(:conditions => ['shipping_address_id IS NULL'])

and

Customer.includes(:orders, :shipping_address).where('shipping_address_id IS NULL')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top