Reputation: 21
I'm working on a project that places "bookings" for a particular property. In order to prevent a property from being double booked, I am trying to return a result of properties that are unavailable during a given time frame. In my Booking model, I have :check_in and :check_out Date fields. My current query is returning dates that are inclusive to the given range only.
For example: Date1 = 04/01/2013 Date2 = 04/15/2013
Returns all Bookings that were placed in that range. But if a Booking was made, say on 03/15/2013 to 04/05/2013 I need it to return that result as well.
Here is my current query:
bookings = Booking.where(check_in: {'$gte' => params[:check_in].to_date, '$lte' => params[:check_out].to_date}, check_out: {'$gte' => params[:check_in].to_date,'$lte' => params[:check_out].to_date})
Upvotes: 1
Views: 235
Reputation: 127
The algorithm you want to use is:
( start1 <= end2 and start2 <= end1 )
Upvotes: 1
Reputation: 21
I'm not sure if this is the most elegant solution, but I got the following query to produce the expected results:
bookings = current_user.organization.corporate_bookings.or(check_in: (params[:check_in].to_date..params[:check_out].to_date)).or(check_out: (params[:check_in].to_date..params[:check_out].to_date)).or(check_in: {"$lte" => params[:check_in].to_date}, check_out: {'$gte' => params[:check_out].to_date})
Upvotes: 1