首页 > 解决方案 > Rails Activerecord:如何排除具有多个关联记录的记录

问题描述

我有下面的查询与所示的关联。

当每辆自行车只有一个预订记录时查询有效,但当自行车有多个预订且一个或多个满足条件而其他不满足时查询失败。由于另一个不满足条件,因此它们会导致关联的自行车被退回。

如何编写查询,以便在至少一个预订满足 where.not 条件时不将自行车作为查询结果返回?

class Bike < ActiveRecord::Base
  has_many :bookings
end 

class Booking < ActiveRecord::Base
  belongs_to :bike
end 

startDate = Date.parse("2018-10-10")
endDate = Date.parse("2018-10-19")

@bikes = Bike.joins(:bookings).where.not("(date_start BETWEEN (?) AND (?)) OR (date_start BETWEEN (?) AND (?)) OR (((?) OR (?)) BETWEEN date_start AND date_end)", startDate, endDate, startDate, endDate, startDate, endDate)

标签: ruby-on-railsrubyrails-activerecord

解决方案


Bike您可以使用以下子查询运行查询Booking

Bike.where.not(
  id: Booking.select('DISTINCT bike_id').where(...)
)

推荐阅读