Class: ExtraValidations::ExistenceValidator

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

Overview

Makes sure that an object/record exists.

Suppose that you have the following class:

class Book
  include ActiveModel::Model
  include ExtraValidations

  attr_accessor :author_id

  validates :author_id, existence: -> (id) { Author.exists?(id) }
end

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

book = Book.new
book.author_id = 100
book.valid? # => false

book.author_id = Author.first.id
book.valid? # => true

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



26
27
28
29
30
# File 'lib/extra_validations/existence_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, id) ⇒ Object

Parameters:

  • record

    An object that has ActiveModel::Validations included

  • attribute (Symbol)
  • id (Integer)


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

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

  success = options[:with].call(id)
  record.errors.add(attribute, :not_found) unless success
end