检查时间之间的重叠

Checking overlaps between times

我尝试创建检查时间重叠的验证。

  scope :overlapping_activity, ->(activity) { where("(start_on, end_on) OVERLAPS (?, ?)",
                                              activity.start_on, activity.end_on }
  validate :not_overlapping_activity

  def not_overlapping_activity
    if Activity.overlapping_activity(self).any?
      errors.add(:base, "Zajęcie w tym okresie koliduje z innymi.")
    end
  end

错误:

ERROR:  function pg_catalog.overlaps(time without time zone, time without time zone, unknown, unknown) is not unique
LINE 1: ...NT(*) FROM "activities" WHERE ((start_on, end_on) OVERLAPS (...

我找到了这个主题:Rails 3.1: Querying Postgres for records within a time range,但我无法在我的解决方案中使用它。当我尝试在范围内添加时间戳时,它显示了另一个语法错误。有人可以告诉我如何正确解决我的问题吗?

我如何尝试使用时间戳:

  scope :overlapping_activity, ->(activity) { where("(start_on::timestamp, end_on::timestamp) OVERLAPS (?, ?)",
                                              timestamp activity.start_on, timestamp activity.end_on) }

我通过这个方法达到了我想要的效果:

validate :not_overlapping_activity

    def not_overlapping_activity
      overlapping_activity = Activity.where(day_of_week: day_of_week)
                                     .where(pool_zone: pool_zone)
      overlapping_activity.each do |oa|
        if (start_on...end_on).overlaps?(oa.start_on...oa.end_on)
          errors.add(:base, 'In this period of time there is some activity.')
        end
      end
    end

如果有人有更好的解决方案请留言。我想变得更好更聪明:)