Sha256: 73dffde1026adeadabd878f35e1d8e324e7a31377f6c4dabc8875f96f26a11d1

Contents?: true

Size: 1.03 KB

Versions: 6

Compression:

Stored size: 1.03 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Validations #:nodoc:
    # Validates whether or not an association is valid or not. Will correctly
    # handle has one and has many associations.
    #
    # Example:
    #
    #   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:
      #
      # <tt>validator.validate_each(document, :name, name)</tt>
      def validate_each(document, attribute, value)
        values = value.is_a?(Array) ? value : [ value ]
        return if values.collect { |doc| doc.nil? || doc.valid? }.all?
        document.errors.add(attribute, :invalid, :default => options[:message], :value => value)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 3 rubygems

Version Path
mongoid-2.0.0.beta.7 lib/mongoid/validations/associated.rb
mongoid-2.0.0.beta.8 lib/mongoid/validations/associated.rb
mongoid-2.0.0.beta.9 lib/mongoid/validations/associated.rb
chhean-mongoid-2.0.1.beta1 lib/mongoid/validations/associated.rb
mongoid-2.0.0.beta.5 lib/mongoid/validations/associated.rb
mongoid-pre-2.0.0.beta1 lib/mongoid/validations/associated.rb