123456789_123456789_123456789_123456789_123456789_

Class: Mongoid::Validatable::PresenceValidator

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ActiveModel::EachValidator
Instance Chain:
self, ActiveModel::EachValidator
Inherits: ActiveModel::EachValidator
  • Object
Defined in: 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

Instance Method Details

#not_present?(value) ⇒ true | false (private)

This method is for internal use only.

For guarding against false values.

Examples:

Is the value not present?

validator.not_present?(value)

Parameters:

  • value (Object)

    The value.

Returns:

  • (true | false)

    If the value is not present.

[ GitHub ]

  
# File 'lib/mongoid/validatable/presence.rb', line 77

def not_present?(value)
  value.blank? && value != false
end

#relation_or_fk_missing?(doc, attr, value) ⇒ true | false (private)

This method is for internal use only.

Returns true if the association is blank or the foreign key is blank.

Examples:

Check is the association or fk is blank.

validator.relation_or_fk_missing(doc, :name, "")

Parameters:

  • doc (Document)

    The document.

  • attr (Symbol)

    The attribute.

  • value (Object)

    The value.

Returns:

  • (true | false)

    If the doc is missing.

[ GitHub ]

  
# File 'lib/mongoid/validatable/presence.rb', line 61

def relation_or_fk_missing?(doc, attr, value)
  return true if value.blank? && doc.send(attr).blank?
  association = doc.relations[attr.to_s]
  association.stores_foreign_key? && doc.send(association.foreign_key).blank?
end

#validate_each(document, attribute, value)

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.

[ GitHub ]

  
# File 'lib/mongoid/validatable/presence.rb', line 28

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