ruby-on-rails - 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)
解决方案
Bike
您可以使用以下子查询运行查询Booking
:
Bike.where.not(
id: Booking.select('DISTINCT bike_id').where(...)
)
推荐阅读
- powershell - 如何访问 Get-Child Registry 输出的属性
- php - 使用 php/dom/xpath 在父 div 类名之后查找下一个 div 类名?
- python - 通过 Youtube 上传,通过 api 设置为私有(锁定)
- mongodb - 使用QueryDSL(Mongodb)获取从开始日期到结束日期的所有行
- visual-studio - Visual Studio - Xamarin iOS 远程模拟器热重载已正确初始化但无法正常工作
- python - python numpy图像数组:获取水平连接图像的列表并将它们排列在网格中
- css - 没有封装时移动导航栏
- reactjs - 向父组件发送初始值
- javafx - JavaFx:在 TableCell 中处理 ImageView 点击
- python - 带有 tqdm 的 Pandas to_csv 进度条