【问题标题】:Simple Association in RailsRails 中的简单关联
【发布时间】:2016-02-24 06:55:09
【问题描述】:

我有两个模型。一个司机和一辆车。司机可以拥有多辆汽车。一辆车可以由许多司机拥有。车型has_many :drivers, through: :car_ownership。这行得通,一切都很好。

但我只想退回所有带司机的汽车,如下所示:

@cars = Car.where.not(drivers: nil)

Car.first.drivers 返回所有 Active Record 模型驱动程序的集合。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord ruby-on-rails-3.2


    【解决方案1】:

    我认为你想要这样的东西(假设你的 car_ownerships 表有一个 driver_id 列):

    Car.joins(:car_ownerships).where('car_ownerships.driver_id IS NOT NULL')
    

    使用纯 Active Record,此查询将是:

    Car.joins(:car_ownerships).where.not(car_ownerships: { driver_id: nil })
    

    【讨论】:

    • 是的。有没有办法在干净的活动记录中做到这一点?
    • 请试试这个:Car.joins(:car_ownerships).where.not(car_ownerships: { driver_id: nil })
    • 太棒了!你也有美好的一天:)
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多