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

Ruby 更改rails模型中自定义验证的优先级,ruby,ruby-on-rails-3,validation,custom-validators,Ruby,Ruby On Rails 3,Validation,Custom Validators,我已经以一种依赖的方式实现了验证,比如如果开始日期格式无效,那么我不想在开始日期运行其他验证 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:

我已经以一种依赖的方式实现了验证,比如如果开始日期格式无效,那么我不想在开始日期运行其他验证

 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”]来检查error对象是否包含错误,如果它不是空的,那么它应该跳过对同一参数的其他验证


但问题是先调用def validate,然后调用的validates_格式。我如何才能改变这一点,从而实现流程。

我刚刚遇到了一个类似的问题;这就是我在保存前使用
标注来修复它的方式:

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

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
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
类条目:学生\u id的唯一性
验证:验证\u规程的\u最大\u条目\u
def验证\u最大\u条目\u用于\u规程
#根据我的标准,设置验证失败-您将在此处进行正则表达式测试
如果验证失败
错误。添加(:最大\u条目,“此处条目过多”)
结束
结束
结束
工作(保存调用前使用):

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
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
类条目:学生\u id的唯一性
def验证\u最大\u条目的\u规程!
#根据我的标准,设置验证失败-您将在此处进行正则表达式测试
如果验证失败
错误。添加(:最大\u条目,“此处条目过多”)
返回错误
结束
结束
结束
注意这些变化:

  • validate\u max\u entries\u for \u规程
    变为
    validate\u max\u entries\u for \u规程
  • 验证方法现在在失败时返回false
  • validate\u max\u entries\u for \u规程
    在保存validate\u max\u entries\u for \u规程之前变为