2012-01-24 2 views
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을 사용했다.

하지만 def validate가 먼저 호출 된 다음 validates_format_of가 문제입니다. 어떻게 흐름을 얻을 수 있도록 이것을 바꿀 수 있습니까?

답변

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 

작업 : - (I 사용자 정의 마지막으로 검증하려는 잘못된 순서로 확인합니다)

가 작동하지

가 :

나는 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_disciplinevalidate_max_entries_for_discipline!
  2. 검증 방법은 지금 실패
  3. validate validate_max_entries_for_discipline에 false를 돌려 before_save validate_max_entries_for_discipline!
을하게된다
관련 문제