2

I have a big problem with date overlapping in my application. I have a model Car which: has_many :reservations and model Reservation which:

belongs_to :car

I'm building search form that will help find cars that not have reservations in the specified date range. My search form looks like this:

= horizontal_simple_form_for :cars, {url: cars_path, method: :get} do |f|
  = f.input :handover_date, as: :string, label: false
  = f.input :return_date, as: :string, label: false
  = f.submit class: 'btn btn-success' 

And in my controller I filter cars based on params:

@cars = Car.joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?", params[:cars][:handover_date], params[:cars][:return_date])

This code is based on (Determine Whether Two Date Ranges Overlap)
but this code not works properly.
In my db I have one car and one reservation for this car. This reservation is from 14 May to 20 May.
Now when I searching and I set in my form handover_date to 10 May and return_date to 16 May it shows me that Car is ready to create reservation but this is false because Car have already reservation from 14 May to 20 May...
I don't have any ideas how to resolve this thing.
Thank's everyone in advance.

Community
  • 1
  • 1
Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133

1 Answers1

2

I was very close to the solution. I must use this:

@cars = Car.joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?", params[:cars][:return_date], params[:cars][:handover_date])

instead of this:

@cars = Car.joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?", params[:cars][:handover_date], params[:cars][:return_date])

Thank's everyone for help.

Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133