Home > Net >  How do I validate an unavailable period
How do I validate an unavailable period

Time:01-23

I'm practicing rails and I would like to know how I would validate a situation.

In this case, it's a car rental project. I have a table of Cars (Autos) and one of Unavailable Period.

When registering a car, I assume that the car is available 100% of the month. If someone rents in a certain period, it must be unavailable so it can't be rented again in the same period, how would I do this validation?

Model

class UnavailablePeriod < ApplicationRecord
   belongs_to :auto
end
class Auto < ApplicationRecord
   belongs_to :rental_company
   belongs_to :category
   has_many :unavailable_periods
end

Any suggestion? content tip to study this? What would be the best way?

model

CodePudding user response:

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.

  •  Tags:  
  • Related