class Mongoid::Validations::PresenceValidator

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

@example Define the presence validator.

class Person
  include Mongoid::Document
  field :title

  validates_presence_of :title
end

Public Instance Methods

validate_each(document, attribute, value) click to toggle source

Validate the document for the attribute and value.

@example Validate the document.

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

@param [ Document ] document The document to validate. @param [ Symbol ] attribute The attribute name. @param [ Object ] value The current value of the field.

@since 2.4.0

# File lib/mongoid/validations/presence.rb, line 27
def validate_each(document, attribute, value)
  field = document.fields[attribute.to_s]
  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