LoginSignup
15
19

More than 5 years have passed since last update.

複数のカラムの値が連携する場合のバリデーション

Posted at

複数のカラムの値が連携する場合のバリデーションはカスタムメソッドで実現できました。
たとえば、Personモデルに真偽値のカラムflg_aflg_bがあり、それらが同時にfalseになってはいけない場合には以下のように記述します。

persons.rb
class Person < ActiveRecord::Base
  validate :flgs_cannot_be_false_at_once

  def flgs_cannot_be_false_at_once
    error_msg = "flg_aとflg_bが同時にfalseになることはできません。"
    errors.add(:flg_a, error_msg) unless flg_a || flg_b
  end
end

モデルにカスタムメソッドflgs_cannot_be_false_at_onceを定義して、メソッド名をシンボルの形でvalidateに渡します。(validates ではなく validate(sがない))

参考:Ruby on Rails Guides: Active Record Validations and Callback 6.2 Custom Methods

15
19
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
15
19