【问题标题】:Rails 3 Custom ValidationRails 3 自定义验证
【发布时间】:2012-04-13 20:23:56
【问题描述】:

我正在尝试创建一个自定义验证,以验证时间表的 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' 

我尝试创建自定义验证器并使用私有验证方法无济于事。有人可以帮我解释一下吗?

【问题讨论】:

  • 只是一个简短的评论,您的方法不遵守 Ruby 的约定。 “dateOverlaps”应命名为“date_overlaps”。

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


【解决方案1】:

尝试替换这个:

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

用这个:

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

【讨论】:

    【解决方案2】:

    代替:

    errors.add_to_base
    

    尝试使用:

    errors.add
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多