associated.rb 2.3 KB
Newer Older
1
module ActiveRecord
2
  module Validations
3 4
    class AssociatedValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
5
        return if (value.is_a?(Array) ? value : [value]).collect{ |r| r.nil? || r.valid? }.all?
6
        record.errors.add(attribute, :invalid, options.merge(:value => value))
7 8 9
      end
    end

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
    module ClassMethods
      # Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
      #
      #   class Book < ActiveRecord::Base
      #     has_many :pages
      #     belongs_to :library
      #
      #     validates_associated :pages, :library
      #   end
      #
      # Warning: If, after the above definition, you then wrote:
      #
      #   class Page < ActiveRecord::Base
      #     belongs_to :book
      #
      #     validates_associated :book
      #   end
      #
28
      # this would specify a circular dependency and cause infinite recursion.
29
      #
30 31
      # NOTE: This validation will not fail if the association hasn't been assigned. If you want to
      # ensure that the association is both present and guaranteed to be valid, you also need to
32
      # use +validates_presence_of+.
33 34
      #
      # Configuration options:
35
      # * <tt>:message</tt> - A custom error message (default is: "is invalid")
X
Xavier Noria 已提交
36 37 38
      # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
      #   validation contexts by default (+nil+), other options are <tt>:create</tt>
      #   and <tt>:update</tt>.
39 40
      # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).  The
41
      #   method, proc or string should return or evaluate to a true or false value.
42 43
      # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
      #   not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).  The
44 45
      #   method, proc or string should return or evaluate to a true or false value.
      def validates_associated(*attr_names)
46
        validates_with AssociatedValidator, _merge_attributes(attr_names)
47 48 49
      end
    end
  end
50
end