Class: ExtraValidations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/extra_validations/uniqueness_validator.rb

Overview

Makes sure that an object/record is unique.

Suppose that you have the following class:

class User
  include ActiveModel::Model
  include ExtraValidations

  attr_accessor :email

  validates :email, uniqueness: ->(email) { User.exists?(email: email) }
end

This validator will execute the given block and, if it returns true, the object will not be valid:

user = User.new
user.email = '[email protected]'
user.valid? # => false

user.email = '[email protected]'
user.valid? # => true

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



26
27
28
29
30
# File 'lib/extra_validations/uniqueness_validator.rb', line 26

def check_validity!
  unless options[:with].is_a?(Proc)
    fail ArgumentError, ':with must be a Proc'
  end
end

#validate_each(record, attribute, value) ⇒ Object

Parameters:

  • record

    An object that has ActiveModel::Validations included

  • attribute (Symbol)
  • value


35
36
37
38
39
40
# File 'lib/extra_validations/uniqueness_validator.rb', line 35

def validate_each(record, attribute, value)
  return if value.blank?

  exists = options[:with].call(value)
  record.errors.add(attribute, :taken) if exists
end