How do I validate an unavailable period
Solution 1:
Instead of an UnavailablePeriod
I would simply have a Rental
model that has a rented_from
and a rented_until
columns (both datetime).
On creation of a new Rental you then only have to check that there is no existing, date overlapping rental. to check that you could use a custom validation like this:
class Rental < ApplicationRecord
belongs_to :auto
validate :rental_period_is_available
private
def rental_period_is_available
return unless Rental
.where.not(id: id)
.where("rented_from < ? && ? < rented_until", rented_until, rented_from)
.exist?
errors.add(:base, "Car is already booked in this time period")
end
end
I suggest reading about custom validations and validations in general in the offical Rails Guides.