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 に答える