[英]PostgreSQL OVERLAPS overator not inclusive of end time - Rails
[英]How check time overlaps in rails
我创建了一个模型: Lecture(start_time, end_time, location) 。 我想编写验证函数来检查新讲座的时间是否与数据库中保存的讲座重叠。 这样我就可以知道该位置在那个时间是否被占用。 我的功能是:
class Lecture < ActiveRecord::Base
validates :title, :position, presence: true
validates :start_time, :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
message: "Incorrect time format" }
validate: time_overlap
def time_overlap
Lecture.all.each do |user|
if (user.start_time - end_time) * (start_time - user.end_time) >= 0
errors.add(:Base, "time overlaps")
end
end
end
end
错误信息: NoMethodError in LecturesController#create undefined method `-@' for nil:NilClass 。 如何以正确的格式编写此函数?
看看 Ruby 2.3.0 的 Time 类: http : //ruby-doc.org/core-2.3.0/Time.html
您可以使用它来检查一个 Time 实例是在另一个 Time 实例之前还是之后,例如:
t1 = Time.now
t2 = Time.now
t1 < t2
=> true
t1 > t2
=> false
因此,要检查数据库中现有讲座期间是否存在给定时间,您可以编写一些 Ruby 来检查提议的讲座的开始时间或结束时间是否在任何现有讲座的开始时间之后和结束时间之前。
假设您有两个时间段,例如:
start_time_a
end_time_a
start_time_b
end_time_b
存在两个时隙之间可能存在重叠的三种可能情况。
1) start_time_b >= start_time_a && start_time_b =< end_time_a
(即,槽 b 在槽 a 的中间某处开始)
2) end_time_b >= start_time_a && end_time_b <= end_time_a
(即,槽 b 在槽 a 之间的某处结束)
3) start_time_b <= start_time_a && end_time_b >= end_time_a
(即slot b比slot a大,并且完全覆盖了它。
如果您检查这三个条件,您可以确定两个时隙之间是否存在重叠。
可以使用start_time_b.between?(start_time_a, end_time_a)
简化条件 1 和 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.