我尝试创建检查时间重叠的验证。
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) }
答案 0 :(得分:1)
我通过这种方法实现了我想要的目标:
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
如果有人有更好的解决方案,请写信。我希望变得更好,更聪明:)