LoginSignup
0
0

More than 1 year has passed since last update.

Rails 条件つきバリデーション

Posted at

条件つきバリデーションとは?

標準であるバリデーションだけでは対応できずに、特定の条件を満たす場合に実行したいバリデーションのこと。

[if],[unless]オプションを使用して記述することで、
特定の条件に対応することができる。

引数にProc,Arrayを使える。

if #特定の条件でバリデーションを行いたい時に使用
unless #特定の条件でバリデーションを行いたくない時に使用

if,unless

class Pass < ApplicationRecord
  validates :number, presence: true, if: :pass_number?

  def pass_number?
    pass_type == "pass"
  end
end
class Money < ApplicationRecord
  #money_validate関数の呼び出し
  validate :money_validate
 
 def money_validate
    unless money.nil? || money > 0.0
  end
end

Proc

呼び出したいProcオブジェクトを:ifや:unlessで使うこともできます。Procオブジェクトを使うと、個別のメソッドを指定する代りに、その場で条件を書けるようになります。ワンライナーに収まる条件を使いたい場合に最適です ~Railsガイド~

class Account < ApplicationRecord
  validates :password, confirmation: true,
    unless: Proc.new { |a| a.password.blank? }
end
~Railsガイド~

リファレンスには上記のように記述されていましたが、
Proc。newでオブジェクトを作成、引数aに渡し、
a.password.blank?で真偽値の判断?

条件付きバリデーションのグループ化

with_options

1つの条件を複数のバリデーションでまとめて処理を行うにはwith_optionsを使用

class User < ApplicationRecord
  with_options if: :is_admin? do |admin|
    admin.validates :password, length: { minimum: 10 }
    admin.validates :email, presence: true
  end
end 
Rails ガイド

if: :is_admin?という条件に対してバリデーションが働く

Array,配列

バリデーションを行なう条件を複数定義する際には、Array 配列を使用

class Computer < ApplicationRecord
  validates :mouse, presence: true,
                    if: [Proc.new  { |c| c.market.retail? }, :desktop?],
                    unless: Proc.new { |c| c.trackpad.present? }
end
Railsガイド

備忘録です。

参考サイト

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