2016-09-21 2 views
0

나는 다음과 같은 한 협회룸 예약 시스템 쿼리

User: 
    has_many :reservations 
    has_many :rooms, through: :reservations 
Room: 
    has_many :reservations 
    has_many :users, through: :reservations 
Reservation: 
    belongs_to :room 
    belongs_to :user 

나는 다음과 같은 한 분야

checkin_date, checkout_date

나는 모든 객실을 찾으려면 주어진 시간 동안 이미 예약되지 않았습니다.

다음 쿼리를 작성했지만 작동하지 않습니다. 수정 또는 더 나은 방법을 제안하십시오.

Room.joins('LEFT JOIN reservations ON reservations.room_id = rooms.id').where.not(
     'reservations.checkin_at < :requested_end_date AND 
     reservations.checkout_at > :requested_start_date', 
     requested_start_date: date_begin, 
     requested_end_date: date_end 
    )  
+0

뭔가 오류? –

+0

@ BartekGładys 예약이없는 경우 비어있는 상태가되므로 모든 객실을 반환해야합니다. – Adt

답변

0

솔루션

class Room < ActiveRecord::Base 

    has_many :reservations 
    has_many :users, through: :reservations 

    def self.find_unreserved date_begin, date_end, category 
    reserved_room_ids = Reservation.on(date_begin, date_end).pluck('DISTINCT room_id') 
    if reserved_room_ids.empty? 
     where(category: category) 
    else 
     where('id NOT IN ?', reserved_room_ids).where(category: category) 
    end 
    end 

end 

class Reservation < ActiveRecord::Base 
    belongs_to :room 
    belongs_to :user 


    scope :on, -> (checkin_date, checkout_date) {where('checkin_at > ? AND checkout_at < ?', checkin_date, checkout_date) } 
end 
0

어쩌면 ...

Room.joins('left join reservations on reservations.room_id = rooms.id') 
      .where('reservations.checkin_at > ? AND reservations.checkout_at < ?', date_begin, date_end) 
      .where('reservations.room_id IS NULL') 
+0

이 경우 예약이 있지만 다른 날짜는 표시되지 않습니다. – Adt

+0

범위가 잘못되었습니다 (나는 방금 그 문제를 해결했습니다 ...). 그러나 그것을 얻지는 않습니다. 사용자 (예약)와 연결되지 않은 방을 얻고 싶습니다. 내 쿼리가 검색하는 것 같아요. 나는 짐작한다) –

+0

나는 일정 기간 동안 예약되지 않은 방을 원한다. 방이 일정 기간 동안 예약되지만 주어진 기간 동안 무료 인 경우가 있습니다. – Adt