验证两个不同的对象,但同一个类

时间:2017-12-13 21:30:32

标签: ruby-on-rails ruby ruby-on-rails-3

所以我有这个模型约会:

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

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

只有一件事进入我的脑海

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在约会模型中

1 个答案:

答案 0 :(得分:2)

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

 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或两者都添加(但会运行多个查询以便更好地编写自己的查询或选择一个字段视为无效)