Reputation: 48443
I have Car
(table cars
) method that has_many
owners (table owners
). How can I choose all cars, that has no owners (== in the table owners
is no one row with respective car's ID)?
Upvotes: 0
Views: 793
Reputation: 1258
You could use this, although it would be very slow if your tables have many records:
Car.where("not exists (select o.id from owners as o where o.car_id = cars.id)")
Upvotes: 1
Reputation: 2269
I would do it as per below in the model....
@cars_without_owners = Car.where("owner_id = ?", nil)
or to be safe....
@cars_without_owners = Car.where("owner_id = ? OR owner_id = ?", nil, "")
Upvotes: 3