我在这里有一个复杂的活动记录查询:
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
查询。
答案 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