From c8bbe9aefae3fdee1eebc8c3e95f5009f5148034 Mon Sep 17 00:00:00 2001 From: Kassio Borges Date: Sun, 8 Nov 2015 10:57:25 -0200 Subject: Improve support for non Active Record objects on `validates_associated` Skipping `marked_for_destruction?` when the associated object does not responds to it make easier to validate virtual associations built on top of Active Model objects and/or serialized objects that implement a `valid?` instance method. --- activerecord/lib/active_record/validations/associated.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb index 32fbaf0a91..b14db85167 100644 --- a/activerecord/lib/active_record/validations/associated.rb +++ b/activerecord/lib/active_record/validations/associated.rb @@ -2,10 +2,16 @@ module ActiveRecord module Validations class AssociatedValidator < ActiveModel::EachValidator #:nodoc: def validate_each(record, attribute, value) - if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any? - record.errors.add(attribute, :invalid, options.merge(:value => value)) + if Array(value).reject { |r| valid_object?(r) }.any? + record.errors.add(attribute, :invalid, options.merge(value: value)) end end + + private + + def valid_object?(record) + (record.respond_to?(:marked_for_destruction?) && record.marked_for_destruction?) || record.valid? + end end module ClassMethods -- cgit v1.2.3