2012-01-24 51 views
2

我已經以依賴的方式實現了驗證,例如start_date格式無效,所以我不想在start_date上運行其他驗證。在rails模型中更改自定義驗證的優先級

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驗證首先被調用,然後是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 

工作(使用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. 驗證方法現在返回失敗
  3. validate validate_max_entries_for_discipline假變得before_save validate_max_entries_for_discipline!