2

我正在创建一个 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

我仍然可以创建重叠的事件并且它们仍然被保存。我在这里做错了什么?

4

1 回答 1

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
于 2013-04-23T03:18:17.913 回答