user984621
user984621

Reputation: 48443

Rails 3 + ActiveRecord - select with condition for association

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

Answers (2)

Christian
Christian

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

Norto23
Norto23

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

Related Questions