反向复杂的活动记录查询

时间:2015-07-31 17:24:13

标签: ruby-on-rails activerecord

我在这里有一个复杂的活动记录查询:

House.includes(:bookings).where("(bookings.status = ? AND bookings.check_in <= ? AND bookings.check_out >= ?) 
  OR (bookings.status = ? AND bookings.check_in <= ? AND bookings.check_out >= ?)", 
  'booked', check_dates[:check_out_date], check_dates[:check_in_date], 
  'blocked', check_dates[:check_out_date], check_dates[:check_in_date]).references(:bookings).uniq

我希望获得不在此查询中的其余House。 但includes无法进行not查询。

1 个答案:

答案 0 :(得分:0)

嗯,有一种简单的方法。

解决这个问题的两种方法:

首先:

ids = House.includes(:bookings).where("(bookings.status = ? AND bookings.check_in <= ? AND bookings.check_out >= ?) 
  OR (bookings.status = ? AND bookings.check_in <= ? AND bookings.check_out >= ?)", 
  'booked', check_dates[:check_out_date], check_dates[:check_in_date], 
  'blocked', check_dates[:check_out_date], check_dates[:check_in_date]).references(:bookings).uniq.ids
result = House.where.now(id: ids)

第二

House.includes(:bookings).where("NOT( (bookings.status = ? AND bookings.check_in <= ? AND bookings.check_out >= ?) 
  OR (bookings.status = ? AND bookings.check_in <= ? AND bookings.check_out >= ?) )", 
  'booked', check_dates[:check_out_date], check_dates[:check_in_date], 
  'blocked', check_dates[:check_out_date], check_dates[:check_in_date]).references(:bookings).uniq