我正在创建一个 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
我仍然可以创建重叠的事件并且它们仍然被保存。我在这里做错了什么?