如何检查新事件(开始时间 - 结束时间)是否与之前的星空时间 - 结束时间(Ruby)不重叠



我正在预约,安排API。我有许多DateTime格式的开始时间和结束时间配对。我需要确保,当我创建一个新的约会时,时间不会与以前的时间重叠。我的意思是,如果我的约会从2015年7月4日9点开始,到2015年4月7日13点结束,我想进行一次确认,这样我就不能从2015年5月7日10点开始,再到2015年7日12点结束。我想比较所有的键值对,以确保新的键值对不在这个范围内。你知道我该怎么做吗?

当您的约会在该约会结束之前开始,在该约会开始之后结束时,会发生重叠。如果没有符合该标准的任命,就没有重叠。

请注意,您还需要考虑特殊情况,即搜索约会会发现一个重叠,但这是您当前正在编辑的约会,因此您可以忽略该约会。

class Appointment < ActiveRecord::Base
  validate :no_overlapping_appointments
  def no_overlapping_appointments
    overlaps = Appointment.where('start_time <= ? AND end_time >= ?', end_time, start_time)
    return if overlaps.empty?
    return if overlaps.count == 1 && overlaps.first.id == id
    errors.add(:start_time, "This appointment overlaps others")
  end
end
class Appointment < ActiveRecord::Base
  validate :duration_not_overlap
  private
  def duration_not_overlap
    verify_time(:starttime)
    verify_time(:endtime)
  end
  # attr is :starttime | :endtime
  def verify_time(attr)
    errors[attr] << 'overlap' if Appointment.where(user_id: user_id, attr => (starttime..endtime)).exists?
  end
end

最新更新