Rails自定义验证有错误但仍然保存?

时间:2013-04-23 03:13:30

标签: ruby-on-rails ruby

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

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

1 个答案:

答案 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