2016-09-21 11 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