2

我已经以依赖的方式实现了验证,比如 start_date 格式是否无效,所以我不想在 start_date 上运行其他验证。

 validates_format_of :available_start_date, :with =>  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}((((\-|\+){1}\d{2}:\d{2}){1})|(z{1}|Z{1}))$/, :message => "must be in the following format: 2011-08-25T00:00:00-04:00"

这将检查特定格式,然后我调用了自定义验证方法,稍后应该运行。

def validate
  super
  check_offer_dates
end

我已经使用 self.errors["start_date"] 检查错误对象是否包含错误,如果它不为空,它应该跳过对同一参数的其他验证。

但问题是先调用 def validate,然后调用 validates_format_of。我怎样才能改变这一点,以便可以实现流程。

4

1 回答 1

1

我刚刚遇到了类似的问题;这就是我使用before_save标注修复它的方式:

不工作(以错误的顺序验证 - 我希望最后进行自定义验证):

class Entry < ActiveRecord::Base
   validates_uniqueness_of :event_id, :within => :student_id
   validate :validate_max_entries_for_discipline

   def validate_max_entries_for_discipline
      # set validation_failed based on my criteria - you'd have your regex test here
      if validation_failed
         errors.add(:maximum_entries, "Too many entries here")
      end
   end
end

工作(使用 before_save 标注):

class Entry < ActiveRecord::Base
   before_save :validate_max_entries_for_discipline!
   validates_uniqueness_of :event_id, :within => :student_id

   def validate_max_entries_for_discipline!
      # set validation_failed based on my criteria - you'd have your regex test here
      if validation_failed
         errors.add(:maximum_entries, "Too many entries here")
         return false
      end
   end
end

注意变化:

  1. validate_max_entries_for_discipline变成validate_max_entries_for_discipline!
  2. 验证方法现在在失败时返回 false
  3. validate validate_max_entries_for_discipline变成before_save validate_max_entries_for_discipline!
于 2013-07-11T17:24:12.733 回答