使用两个不同但相同的对象进行验证 class

validation with two diffrent objects but same class

所以我有这个模特约会:

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

现在是这样的情况:如果有人想在同一天同一时间预约,我想得到错误。所以我必须比较相同 class 的两个对象,但我不知道该怎么做。

我只想到一件事

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

是的 employee_id 在约会模型中

您可以像这样简单地使用模型验证

 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

显然,如果您的约会有时间范围,例如30 分钟后您需要更改它,因为它只会检查完全匹配。

也可以处理完全匹配,但正如@SebastianPalma 提到的那样进行唯一性检查

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

第一个将错误添加到 appointment_date,第二个将错误添加到 appointment_time 或两者都添加(但 运行 多个查询更好地编写您自己的或选择一个字段到视为无效)