Ruby on Rails ActiveRecord Validations Grouping validation


Example

Sometimes it is useful to have multiple validations use one condition. It can be easily achieved using 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

All validations inside of the with_options block will have automatically passed the condition if: :is_admin?