1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Creates error messages of a has_many or has_one child model when validating an instance of a parent model and adds them to
# the parent.
# Example
#
# class Garage < ActiveRecord::Base
#   has_many :cars
#   validates_associated_attributes :cars
# end
#
# class Car < ActiveRecord::Base
#   validates_presence_of :license_plate, :message => 'must be registered'
# end
#
# garage.valid? ==> "License plate must be registered"
# (The standard message would be "Car is invalid" and thus much less instructive"
#
# (c) 2009, Wolfram Arnold, [email protected], www.wtaconsulting.net

module ValidatesAssociatedAttributes
  module ActiveRecord::Validations::ClassMethods
    def validates_associated_attributes(*associations)
      class_eval do
        validates_each(associations) do |record, associate_name, value|
          associates = value.respond_to?(:each) ? value : [value]  # this lets you use it with both has_one and has_many
          associates.each do |associate|
            if associate && !associate.valid?
              associate.errors.each do |key, value|
                record.errors.add(key, value)
              end
            end
          end
        end
      end
    end
  end
end