Ruby on rails 使用两个不同对象但属于同一类的验证

Ruby on rails 使用两个不同对象但属于同一类的验证,ruby-on-rails,ruby,ruby-on-rails-3,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]) <----- t

所以我有一个典型的约会:

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
def allready\u预订了吗?

@employee=employee.find(params[: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\u date
中,第二个添加到
appointment\u time
中,或者两个都添加(但是运行多个查询会更好地编写自己的查询,或者选择一个字段将其视为无效)

您考虑过使用PORO服务类吗?这是一个很好的用例,我明天再考虑,也许会有另一个答案,但还是要谢谢你!您可以通过传递作用域来验证唯一性
验证:约会日期,唯一性:{scope::约会时间}
@SebastianPalma-这将不允许在同一日期/时间进行任何约会,对吗?也许可以将
employee\u id
添加到唯一性范围?第一个解决方案很有趣,我必须将其保存在某个地方,但第二个解决方案非常有效!我已经设定了这样的时间:7:30-8:00-8:30-14:00,一切正常。谢谢你的回答!