From f4e484a18be2572c961dc5c7d5278bc56fb31100 Mon Sep 17 00:00:00 2001 From: David Schovanec Date: Thu, 18 May 2017 15:30:03 +0200 Subject: [PATCH] Preserve mutation changes when updating parent_id --- lib/closure_tree/hierarchy_maintenance.rb | 34 +++++++++++++++++------ 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/lib/closure_tree/hierarchy_maintenance.rb b/lib/closure_tree/hierarchy_maintenance.rb index e9fe761e..ef2ca0f7 100644 --- a/lib/closure_tree/hierarchy_maintenance.rb +++ b/lib/closure_tree/hierarchy_maintenance.rb @@ -38,20 +38,38 @@ def _ct_after_save as_5_1 = ActiveSupport.version >= Gem::Version.new('5.1.0') changes_method = as_5_1 ? :saved_changes : :changes - if public_send(changes_method)[_ct.parent_column_name] || @was_new_record - rebuild! - end - if public_send(changes_method)[_ct.parent_column_name] && !@was_new_record - # Resetting the ancestral collections addresses - # https://github.com/mceachen/closure_tree/issues/68 - ancestor_hierarchies.reload - self_and_ancestors.reload + if public_send(changes_method)[_ct.parent_column_name] + _ct_persist_activerecord_state do + if @was_new_record + rebuild! + else + # Resetting the ancestral collections addresses + # https://github.com/mceachen/closure_tree/issues/68 + ancestor_hierarchies.reload + self_and_ancestors.reload + end + end end + @was_new_record = false # we aren't new anymore. @_ct_skip_sort_order_maintenance = false # only skip once. true # don't cancel anything. end + def _ct_persist_activerecord_state &block + tmp_previous_mutation_tracker = @previous_mutation_tracker + tmp_mutation_tracker = @mutation_tracker + tmp_mutations_from_database = @mutations_from_database + tmp_mutations_before_last_save = @mutations_before_last_save + + yield block + + @previous_mutation_tracker = tmp_previous_mutation_tracker + @mutation_tracker = tmp_mutation_tracker + @mutations_from_database = tmp_mutations_from_database + @mutations_before_last_save = tmp_mutations_before_last_save + end + def _ct_before_destroy _ct.with_advisory_lock do delete_hierarchy_references