From 6349ad300f2cace625b1c733410c4a39c91028ec Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Sun, 27 May 2018 01:40:00 +0900 Subject: Fix `belongs_to_counter_cache_after_update` to respect polymorphic type change --- .../lib/active_record/associations/belongs_to_association.rb | 4 ++++ .../active_record/associations/belongs_to_polymorphic_association.rb | 5 ++++- activerecord/lib/active_record/associations/builder/belongs_to.rb | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb index 121592733c..cea2570ac4 100644 --- a/activerecord/lib/active_record/associations/belongs_to_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_association.rb @@ -42,6 +42,10 @@ module ActiveRecord update_counters(1) end + def target_changed? + owner.saved_change_to_attribute?(reflection.foreign_key) + end + private def replace(record) if record diff --git a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb index 75b4c4481a..3fd2fb5f67 100644 --- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb +++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb @@ -9,8 +9,11 @@ module ActiveRecord type.presence && type.constantize end - private + def target_changed? + super || owner.saved_change_to_attribute?(reflection.foreign_type) + end + private def replace_keys(record) super owner[reflection.foreign_type] = record ? record.class.polymorphic_name : nil diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index 1dd6e5bed8..9e012285e5 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -36,7 +36,7 @@ module ActiveRecord::Associations::Builder # :nodoc: if (@_after_replace_counter_called ||= false) @_after_replace_counter_called = false - elsif saved_change_to_attribute?(foreign_key) && !new_record? + elsif association(reflection.name).target_changed? if reflection.polymorphic? model = attribute_in_database(reflection.foreign_type).try(:constantize) model_was = attribute_before_last_save(reflection.foreign_type).try(:constantize) -- cgit v1.2.3