Class: ExtraValidations::ExistenceValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ExtraValidations::ExistenceValidator
- 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. = 100
book.valid? # => false
book. = 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 [:with].is_a?(Proc) fail ArgumentError, ':with must be a Proc' end end |
#validate_each(record, attribute, id) ⇒ Object
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 = [:with].call(id) record.errors.add(attribute, :not_found) unless success end |