使用连接 Rails 的嵌套记录
Nested records using join Rails
我有这些模型
class Car < ApplicationRecord
has_many :car_locations ,:dependent=>:destroy
has_many :rides,:dependent=>:destroy
end
class CarLocation < ApplicationRecord
belongs_to :car
end
class Ride < ApplicationRecord
belongs_to :car
end
boolean
类型的 Ride
模型中有一个 status
属性。
现在我想要那些 CarLocation
的乘车状态为 false
或没有乘车的最低复杂度。
I want those Car Locations whose car rides status
is false
CarLocation.joins(car: :rides).where(rides: { status: false })
or don't have any car ride
CarLocation.includes(car: :rides)
.where(rides: { id: nil })
.references(:rides)
将两者结合在一起:
CarLocation.includes(car: :rides)
.where('rides.status = false OR rides.id IS NULL')
.references(:rides)
我有这些模型
class Car < ApplicationRecord
has_many :car_locations ,:dependent=>:destroy
has_many :rides,:dependent=>:destroy
end
class CarLocation < ApplicationRecord
belongs_to :car
end
class Ride < ApplicationRecord
belongs_to :car
end
boolean
类型的 Ride
模型中有一个 status
属性。
现在我想要那些 CarLocation
的乘车状态为 false
或没有乘车的最低复杂度。
I want those Car Locations whose car rides
status
isfalse
CarLocation.joins(car: :rides).where(rides: { status: false })
or don't have any car ride
CarLocation.includes(car: :rides)
.where(rides: { id: nil })
.references(:rides)
将两者结合在一起:
CarLocation.includes(car: :rides)
.where('rides.status = false OR rides.id IS NULL')
.references(:rides)