Rails 3自定义验证

时间:2012-04-13 20:23:56

标签: ruby-on-rails-3 validation model

我正在尝试创建一个自定义验证,用于验证计划的start_date和end_date与其他计划不重叠

class Schedule < ActiveRecord::Base
#has many scheduleTimes (fk in scheduleTime)
has_many :scheduletimes, :inverse_of => :schedule 

validate :dateOverlaps?

scope :active, lambda {
 where('? between start_date and end_date', Date.today)
}
def dateOverlaps?
  results = ActiveRecord::Base.connection.execute("Select (start_date::DATE, end_date::DATE) OVERLAPS ('#{self.start_date}'::DATE, '#{self.end_date}'::DATE) from schedules;")
  errors.add_to_base("Date ranges cannot overlap with another schedule") if                   results.first["overlaps"] == 't'
end

但是,这会导致

NoMethodError: undefined method `add_to_base' 

我尝试过创建自定义验证器并使用私有验证方法无济于事。有人可以为我发光吗?

2 个答案:

答案 0 :(得分:9)

尝试替换它:

errors.add_to_base("Date ranges cannot overlap with another schedule")

用这个:

errors.add(:base, "Date ranges cannot overlap with another schedule")

答案 1 :(得分:1)

而不是:

errors.add_to_base

尝试使用:

errors.add