LoginSignup
0
0

More than 3 years have passed since last update.

ActiveModelのvalidateが発火されない時に

Posted at

最近RailsのViewを使うケースより、APIの開発ケースが増えたので、ActiveModelの使う機会が以前より、グーと増えた気がした。が、すごく簡単なことで、ハマってしまったので、メモ形式で共有します。

例えば、ActiveModelを使った以下のような簡単なクラスがあるとしよう。

class SearchForm
  include ActiveModel::Model
  attr_accessor :from_date, :to_date
  validate :check_something

  def check_something
    ・・・
  end
end

Controller側では以下のように利用するとしよう。

form = SearchForm.new(params)

インスタンスの作成時、当然、カスタムバリエーション用のメソッドが実行されない。
「えっ?なぜcheck_somethingが実行されないの?」という簡単なミスにハマったことがあった。
valid? or invalid?を呼ばない限り、発火しないのは当然のことだが、、、ORZ

以下のように

form.valid? 
# or
form.invalid? 

みなさんは、このような経験がないでしょうか?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0