1

I'm developing a booking system in Rails 3.1. I have created a model for a Booking:

# == Schema Information
#
# Table name: bookings
#
# id           :integer         not null, primary key
# product_id   :integer
# customer_id  :integer
# booked_from  :datetime
# booked_to    :datetime
# paid         :boolean
# payment_type :string(255)
# created_at   :datetime
# updated_at   :datetime
#

So what I want to do is to validate each entry and check whether the desired time period (booked_from - booked_to) is overlapping any period of another booking with the same product_id. The products also have an available_from and available_to field which it also has to validate against.

How do I do this?

samuel02
  • 343
  • 5
  • 15

1 Answers1

3

Check if this works:

class Booking
  validate :booking_period_not_overlapped
  private
    def booking_period_not_overlapped
      unless Booking.where(
        '(booked_from <= ? AND booked_to >= ?) OR (booked_from >= ? AND booked_from <= ?)',
        booked_from, booked_from,
        booked_from, booked_to
      ).empty?
        errors.add(:booked_from, 'Invalid period.')
      end
    end
end

It just checks if there is any existing records whose booked_from and booked_to satisfy one of the following conditions (suppose your new booking is from 16:00 to 17:00):

  1. it starts before the new booking, and not yet ended (e.g. 15:00 - 16:30 or 15:00 - 17:30)
  2. it starts within the new booking period (e.g. 16:20 - 16:50 or 16:30 - 17:30)
Limbo Peng
  • 2,485
  • 19
  • 12
  • Works after adding errors.add(....) unless Booking.where... Add it to your answer so I can check it as being correct, also sqlite complains about the slash, so move up the line and remove it. Thanks! – samuel02 Mar 23 '12 at 15:21