I am making a hotel reservation system. I have models for User, Room, and Reservation. I have used associations to link as follows: (note, pseudo code)
User has_many Reservations
User has_many Rooms, through Reservations
Room has_many Reservations
Room has_many Users, through Reservations
Reservation belongs_to Users
Reservation belongs_to Reservations
All is working fine, for example I can list a user's reservations and rooms. Now I need to list all rooms which aren't currently reserved. I have tried the following which doesn't seem to work:
reservations = Reservation.where('start > ? AND end < ?', Time.now, Time.now).select('room_id')
if reservations.empty?
@rooms = Room.all
else
@rooms = Room.where('id not in (?)',
reservations)
end
I wondered if there is an ActiveRecord method which would do this for me? I tried forcing a LEFT JOIN on rooms to get all rooms where the end date < now but that didn't work either.
Many thanks for your help!