【问题标题】:Active record get all instance that do not match condition活动记录获取所有不匹配条件的实例
【发布时间】:2016-09-26 23:17:25
【问题描述】:

我有以下 AR 查询,它返回一组房间(在给定时间段内不可用的房间):

rooms = Room.joins(:bookings).where("(bookings.start_date >= ? AND bookings.start_date <= ?) OR (bookings.end_date >= ? AND bookings.end_date <= ?) OR (bookings.start_date <= ? AND bookings.end_date >= ?)", from, to, from, to, from, to)

我想修改那个查询,让它返回所有其他房间;那是在请求的时间段内可用的那些。正确的结果如下:

all_rooms = Room.all
available_rooms = all_rooms - rooms

但我直接想在单个查询中获取可用房间。我已经添加了一个 .not 但它没有给我正确的结果:

rooms = Room.joins(:bookings).where.not("(bookings.start_date >= ? AND bookings.start_date <= ?) OR (bookings.end_date >= ? AND bookings.end_date <= ?) OR (bookings.start_date <= ? AND bookings.end_date >= ?)", from, to, from, to, from, to)

我应该如何修改查询?

【问题讨论】:

    标签: ruby-on-rails activerecord querying


    【解决方案1】:

    假设:

    A = (bookings.start_date >= ? AND bookings.start_date <= ?)
    B = (bookings.end_date >= ? AND bookings.end_date <= ?) 
    C = (bookings.start_date <= ? AND bookings.end_date >= ?)
    first_logic  = A or B or C
    second_logic = not(first_logic) = not(A or B or C) = not(A) and not(B) and not(C)
    

    available_roomssecond_logic 的条件,所以会是这样的:

    available_rooms = Room.joins(:bookings)
                          .where.not("bookings.start_date >= ? AND bookings.start_date <= ?", from, to)
                          .where.not("bookings.end_date >= ? AND bookings.end_date <= ?", from, to)
                          .where.not("bookings.start_date <= ? AND bookings.end_date >= ?", from, to)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2012-07-31
      • 2021-11-21
      相关资源
      最近更新 更多