LoginSignup
0
1

More than 3 years have passed since last update.

Railsのカスタムバリデーション(ActiveModel::Validator)

Last updated at Posted at 2020-12-06

はじめに

独自のバリデーションを実装するvalidates_withに関して簡単にまとめます。

バリデーションの作り方

app/validatorsフォルダにカスタムバリデーションを書いていきます。

例えば、退社済みのスタッフの場合エラーが出る様なバリデーションを作る場合、下記の様になります。

class ActiveStaffValidator < ActiveModel::Validator
  def validate(record)
    if record.end_date < Date.today
      record.errors[:base] << "退社済みのスタッフです。"
    end
  end
end

使い方

使い方としては、対象のモデルのファイルに

validates_with ActiveStaffValidator

と記載するだけです。

0
1
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
1