Class: Mongoid::Validations::ReferencedValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mongoid/validations/referenced.rb

Overview

Validates whether or not an association is valid or not. Will correctly handle has one and has many associations. Will not load associations if they aren’t already in memory.

Examples:

Set up the association validations.


class Person
  include Mongoid::Document
  references_many :posts, :validate => true
end

Instance Method Summary collapse

Instance Method Details

#validate(document) ⇒ Object

Validate the document for the initialized attributes. Will not load any association that’s not currently loaded.

Parameters:

  • document (Document)

    The document to validate.



21
22
23
24
25
26
# File 'lib/mongoid/validations/referenced.rb', line 21

def validate(document)
  attributes.each do |attribute|
    value = document.instance_variable_get("@#{attribute}".to_sym)
    validate_each(document, attribute, value)
  end
end

#validate_each(document, attribute, value) ⇒ Object

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

Examples:

Validate the loaded association.

validator.validate_each(document, :name, name)

Parameters:

  • document (Document)

    The document to validate.

  • attribute (Symbol)

    The relation to validate.

  • value (Object)

    The value of the relation.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/mongoid/validations/referenced.rb', line 38

def validate_each(document, attribute, value)
  document.validated = true
  valid =
    if !value || !value.target
      true
    else
      Array.wrap(value).collect do |doc|
        if doc.nil? || (!doc.changed? && !doc.new_record?)
          true
        else
          doc.validated? ? true : doc.valid?
        end
      end.all?
    end
  document.validated = false
  return if valid
  document.errors.add(attribute, :invalid, options.merge(:value => value))
end