Ruby on rails 3 轨道3和x2B;ActiveRecord-选择与关联的条件
我有Ruby on rails 3 轨道3和x2B;ActiveRecord-选择与关联的条件,ruby-on-rails-3,activerecord,select,model,associations,Ruby On Rails 3,Activerecord,Select,Model,Associations,我有Car(表cars)方法有很多车主(表车主)。我如何选择所有没有车主的汽车(=在表中,车主没有一行有相应的汽车ID)?我会按照以下模型进行选择 @cars_without_owners = Car.where("owner_id = ?", nil) 或者为了安全 @cars_without_owners = Car.where("owner_id = ? OR owner_id = ?", nil, "") 我会按照下面的模型做 @cars_without_owners = Car.w
Car
(表cars
)方法有很多车主(表车主
)。我如何选择所有没有车主的汽车(=在表中,车主
没有一行有相应的汽车ID)?我会按照以下模型进行选择
@cars_without_owners = Car.where("owner_id = ?", nil)
或者为了安全
@cars_without_owners = Car.where("owner_id = ? OR owner_id = ?", nil, "")
我会按照下面的模型做
@cars_without_owners = Car.where("owner_id = ?", nil)
或者为了安全
@cars_without_owners = Car.where("owner_id = ? OR owner_id = ?", nil, "")
您可以使用它,但如果您的表有许多记录,则速度会非常慢:
Car.where("not exists (select o.id from owners as o where o.car_id = cars.id)")
您可以使用它,但如果您的表有许多记录,则速度会非常慢:
Car.where("not exists (select o.id from owners as o where o.car_id = cars.id)")