aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorRyuta Kamizono <kamipo@gmail.com>2018-05-27 01:40:00 +0900
committerRyuta Kamizono <kamipo@gmail.com>2018-05-27 02:33:47 +0900
commit6349ad300f2cace625b1c733410c4a39c91028ec (patch)
tree1146dfc488052e55fad9092da111a5e6070e3036 /activerecord/lib
parentcbab69c2789ff49bd9e3580eba0ac273190c9dc7 (diff)
downloadrails-6349ad300f2cace625b1c733410c4a39c91028ec.tar.gz
rails-6349ad300f2cace625b1c733410c4a39c91028ec.tar.bz2
rails-6349ad300f2cace625b1c733410c4a39c91028ec.zip
Fix `belongs_to_counter_cache_after_update` to respect polymorphic type change
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb4
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb5
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb2
3 files changed, 9 insertions, 2 deletions
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)