我正在创建一个rails应用来管理事件,我想添加验证以检查事件是否与另一个事件重叠。
这是我的自定义验证码,用于检查重叠事件:
class Event < ActiveRecord::Base
attr_accessible :full_date, :start_hour, :end_hour, :address
validate :no_overlapping_events
def no_overlapping_events
overlap = false
same_date = Event.where(:full_date => self.full_date).where("id != ?", self.id).where(:address => self.address)
same_date.each do |t|
if self.start_hour <= t.start_hour
if self.end_hour >= t.start_hour
overlap = true
break
end
end
end
if overlap == true
errors.add(:base, "Can't have overlapping events!")
end
end
end
我仍然可以创建重叠的事件,但它们仍在保存中。我在这里做错了什么?
答案 0 :(得分:3)
您的自定义验证方法过早“结束”。尝试:
class Event < ActiveRecord::Base
attr_accessible :full_date, :start_hour, :end_hour, :address
validate :no_overlapping_events
def no_overlapping_events
overlap = false
same_date = Event.where(:full_date => self.full_date).where("id != ?", self.id).where(:address => self.address)
same_date.each do |t|
if self.start_hour <= t.start_hour
if self.end_hour >= t.start_hour
overlap = true
break
end
end
end
if overlap == true
errors.add(:base, "Can't have overlapping events!")
end
end
end
另外,作为一个逻辑错误,在下列情况下如何:
self.start_hour > t.start_hour and self.start_hour < t.end_hour