【问题标题】:Rails 3 + ActiveRecord - select with condition for associationRails 3 + ActiveRecord - 选择关联条件
【发布时间】:2012-03-29 23:52:32
【问题描述】:

我有Car(表cars)方法,has_many拥有者(表owners)。如何选择所有没有车主的汽车(== 表中owners 没有一行具有相应汽车的 ID)?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord select model associations


    【解决方案1】:

    我会按照下面的模型来做......

    @cars_without_owners = Car.where("owner_id = ?", nil)
    

    为了安全……

    @cars_without_owners = Car.where("owner_id = ? OR owner_id = ?", nil, "")
    

    【讨论】:

      【解决方案2】:

      你可以使用这个,虽然如果你的表有很多记录会很慢:

      Car.where("not exists (select o.id from owners as o where o.car_id = cars.id)")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        相关资源
        最近更新 更多