更改rails模型中自定义验证的优先级

时间:2012-01-24 09:18:19

标签: ruby ruby-on-rails-3 validation custom-validators

我已经以依赖方式实现了验证,比如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。我怎样才能改变这一点,以便实现流程。

1 个答案:

答案 0 :(得分: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!