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!
What exactly did not work? I suggest you create an
onscope to filter all the reservations, which are active on a given Date. Then you can usepluckto get an array of room ids to then fetch the Rooms themselves.The code could look something like (warning, written from the top of my head, not tested):
Now you can use
Room.free_onorRoom.free_on(1.day.ago)to get the free rooms for a given day. I also added the method to get to the reserved rooms.