: O. Yuanying

一部のフィールドのみvalidを実行する

一部のフィールドのみvalidを実行するっていったいどういう状況なんだろうなーと、小一時間考えたところ、ウィザード形式の入力フォームかなと気づいた。

さて、そんなこんなで validation に関するドキュメントを読んでみると、それぞれの validates* メソッドに以下のようなオプションが。

  • if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.
  • unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

どうもオプションで指定したメソッド/ブロックを評価して、そのバリデーションを行うかどうか決めれるらしい。

モデル内にいつその検証を行うかどうかの情報が与えられているのならばこれを使った方が良いんじゃない?って気がするし多分Rails的な気がする。