简体   繁体   中英

validation with two diffrent objects but same class

So i have this model Appointment:

validates :purpose, :extra, :appointment_date, :appointment_time, presence: true

and now this is situation: i want to get error if someone will want to make appointment in the same day and the same time. So i have to compare two objects of the same class and i have no idea how i can do it.

only one thing comes into my mind

def allready_booked?
  @employee = Employee.find(params[:employee_id]) <----- this is the part i dont know how to do it
  @appointments = Appointment.where(appointment_date: appointment_date).where(employee_id: employee.id)
  @appoitnments.each do |appo|
    if(appo.appointment_date == appointment_date)
      errors.add(:appoitnemnt_date, "is already booked")
    end
  end
end

And yes employee_id is in Appointment model

You could simply use a model validation like so

 class Appointment < ActiveRecord::Base
    validate :available_time

    private
    def available_time
      other_appointments = Appointment.where(
                             appointment_date: self.appointment_date,
                             appointment_time: self.appointment_time,
                             employee_id: self.employee_id
                           ) 
      unless other_appointments.empty?
        [:appointment_date,:appointment_time].each do |attr|
          errors.add(attr,"is not available")
        end
      end       
    end
 end

Obviously if your appointments have a time frame eg 30 minutes you would need to alter this as it will only check against exact matches.

Also exact matches can be handled but uniqueness checking as mentioned by @SebastianPalma like so

class Appointment < ActiveRecord::Base
  validates :appointment_date, uniqueness: {scope: [:employee_id,:appointment_time] }
  # Or 
  validates :appointment_time, uniqueness: {scope: [:employee_id, :appointment_date] } 
end

The first will add the error to appointment_date the second to appointment_time or both adds both (but will run multiple queries so better to write your own or pick one field to considered invalid)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM