Class: Mongoid::Validatable::AssociatedValidator

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

Overview

Validates whether or not an association is valid or not. Will correctly handle has one and has many associations.

Examples:

Set up the association validations.


class Person
  include Mongoid::Document
  embeds_one :name
  embeds_many :addresses

  validates_associated :name, :addresses
end

Instance Method Summary collapse

Instance Method Details

#validate_each(document, attribute, value) ⇒ Object

Validates that the associations provided are either all nil or all valid. If neither is true then the appropriate errors will be added to the parent document.

Examples:

Validate the association.

validator.validate_each(document, :name, name)

Parameters:

  • document (Document)

    The document to validate.

  • attribute (Symbol)

    The association to validate.

  • value (Object)

    The value of the association.

Since:

  • 2.0.0



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

def validate_each(document, attribute, value)
  begin
    document.begin_validate
    valid = Array.wrap(value).collect do |doc|
      if doc.nil? || doc.flagged_for_destroy?
        true
      else
        doc.validated? ? true : doc.valid?
      end
    end.all?
  ensure
    document.exit_validate
  end
  document.errors.add(attribute, :invalid, **options) unless valid
end