Sha256: 71235e139ba98a3392e7f645a61eab5926d222ee4fd9e4cefca9069c8ab63e93

Contents?: true

Size: 1.03 KB

Versions: 1

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
    #     embed_one :name
    #     embed_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

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-2.0.0.alpha lib/mongoid/validations/associated.rb