From 86d7c4af4dc0f652926036ec4933f548af0105a2 Mon Sep 17 00:00:00 2001 From: Keenan Brock Date: Fri, 3 Mar 2023 14:09:28 -0500 Subject: [PATCH] fix increase_parent_counter_cache callback no longer incrementing counter when callbacks are disabled (to make increase and decrease consistent) Update parent_counter_cache now respects @_trigger_update_callback Not sure if update follows the same rules as destroy introduced in 63b42f53 But would like both trees to follow the same logic There are reports of incorrect cache counts. So when insert and destroy have different guard clauses, it is suspect. --- lib/ancestry/instance_methods.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/ancestry/instance_methods.rb b/lib/ancestry/instance_methods.rb index 08427c2b..0965ccda 100644 --- a/lib/ancestry/instance_methods.rb +++ b/lib/ancestry/instance_methods.rb @@ -62,6 +62,7 @@ def touch_ancestors_callback # Counter Cache def increase_parent_counter_cache + return if ancestry_callbacks_disabled? self.ancestry_base_class.increment_counter _counter_cache_column, parent_id end @@ -78,14 +79,18 @@ def decrease_parent_counter_cache end def update_parent_counter_cache - changed = saved_change_to_attribute?(self.ancestry_base_class.ancestry_column) - - return unless changed + # @_trigger_update_callback comes from activerecord, which makes sure only once decrement when concurrent deletion. + # but @_trigger_update_callback began after rails@5.1.0.alpha. + # https://github.com/rails/rails/blob/v5.2.0/activerecord/lib/active_record/persistence.rb#L340 + # https://github.com/rails/rails/pull/27248 + return if defined?(@_trigger_update_callback) && !@_trigger_update_callback + return unless saved_change_to_attribute?(self.ancestry_base_class.ancestry_column) if parent_id_was = parent_id_before_last_save self.ancestry_base_class.decrement_counter _counter_cache_column, parent_id_was end + # TODO: use increase_parent_counter_cache instead? parent_id && self.ancestry_base_class.increment_counter(_counter_cache_column, parent_id) end