Class: Mongoid::Validatable::PresenceValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
build/mongoid-7.3/lib/mongoid/validatable/presence.rb

Overview

Validates that the specified attributes are not blank (as defined by Object#blank?).

Examples:

Define the presence validator.


class Person
  include Mongoid::Document
  field :title

  validates_presence_of :title
end

Instance Method Summary collapse

Instance Method Details

#validate_each(document, attribute, value) ⇒ Object

Validate the document for the attribute and value.

Examples:

Validate the document.

validator.validate_each(doc, :title, "")

Parameters:

  • document (Document)

    The document to validate.

  • attribute (Symbol)

    The attribute name.

  • value (Object)

    The current value of the field.

Since:

  • 2.4.0



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'build/mongoid-7.3/lib/mongoid/validatable/presence.rb', line 30

def validate_each(document, attribute, value)
  field = document.fields[document.database_field_name(attribute)]
  if field.try(:localized?) && !value.blank?
    value.each_pair do |_locale, _value|
      document.errors.add(
        attribute,
        :blank_in_locale,
        **options.merge(location: _locale)
      ) if not_present?(_value)
    end
  elsif document.relations.has_key?(attribute.to_s)
    if relation_or_fk_missing?(document, attribute, value)
      document.errors.add(attribute, :blank, **options)
    end
  else
    document.errors.add(attribute, :blank, **options) if not_present?(value)
  end
end