Sha256: 8695b61913afedb0660551b71dc430039425a0b1bf0376b93e6b6c7d90f8604d

Contents?: true

Size: 1.38 KB

Versions: 7

Compression:

Stored size: 1.38 KB

Contents

# encoding: utf-8
module Mongoid
  module Validations

    # Validates whether or not an association is valid or not. Will correctly
    # handle has one and has many associations.
    #
    # @example Set up the association validations.
    #
    #   class Person
    #     include Mongoid::Document
    #     embeds_one :name
    #     embeds_many :addresses
    #
    #     validates_associated :name, :addresses
    #   end
    class AssociatedValidator < ActiveModel::EachValidator

      # 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.
      #
      # @example Validate the association.
      #   validator.validate_each(document, :name, name)
      #
      # @param [ Document ] document The document to validate.
      # @param [ Symbol ] attribute The relation to validate.
      # @param [ Object ] value The value of the relation.
      def validate_each(document, attribute, value)
        begin
          document.begin_validate
          valid = Array.wrap(value).collect do |doc|
            if doc.nil?
              true
            else
              doc.validated? ? true : doc.valid?
            end
          end.all?
        ensure
          document.exit_validate
        end
        document.errors.add(attribute, :invalid) unless valid
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
mongoid-3.0.5 lib/mongoid/validations/associated.rb
mongoid-3.0.4 lib/mongoid/validations/associated.rb
mongoid-3.0.3 lib/mongoid/validations/associated.rb
mongoid-3.0.2 lib/mongoid/validations/associated.rb
mongoid-3.0.1 lib/mongoid/validations/associated.rb
mongoid-3.0.0 lib/mongoid/validations/associated.rb
mongoid-3.0.0.rc lib/mongoid/validations/associated.rb