From 44cb3f9308581d1553cafeadb1b50d630ce8f846 Mon Sep 17 00:00:00 2001 From: Chris Andreae Date: Fri, 5 Jul 2019 18:54:39 +0900 Subject: [PATCH] Propagate child changes through association manipulation --- .../active_record/association_manipulation.rb | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/view_model/active_record/association_manipulation.rb b/lib/view_model/active_record/association_manipulation.rb index 2b224413..24e8855c 100644 --- a/lib/view_model/active_record/association_manipulation.rb +++ b/lib/view_model/active_record/association_manipulation.rb @@ -176,15 +176,26 @@ def append_associated(association_name, subtree_hash_or_hashes, references: {}, child_context = self.context_for_child(association_name, context: deserialize_context) updated_viewmodels = update_context.run!(deserialize_context: child_context) + # Propagate changes and finalize the parent + updated_viewmodels.each do |child| + child_changes = child.previous_changes + + if association_data.nested? + nested_children_changed! if child_changes.changed_nested_tree? + referenced_children_changed! if child_changes.changed_referenced_children? + elsif association_data.owned? + referenced_children_changed! if child_changes.changed_owned_tree? + end + end + + final_changes = self.clear_changes! + if association_data.through? updated_viewmodels.map! do |direct_vm| direct_vm._read_association(association_data.indirect_reflection.name) end end - # Finalize the parent - final_changes = self.clear_changes! - # Could happen if hooks attempted to change the parent, which aren't # valid since we're only editing children here. unless final_changes.contained_to?(associations: [association_name.to_s]) @@ -268,7 +279,11 @@ def delete_associated(association_name, associated_id, type: nil, deserialize_co association.delete(child_vm.model) end - self.referenced_children_changed! if association_data.owned? + if association_data.nested? + nested_children_changed! + elsif association_data.owned? + referenced_children_changed! + end final_changes = self.clear_changes! @@ -286,7 +301,7 @@ def delete_associated(association_name, associated_id, type: nil, deserialize_co private - def construct_direct_append_updates(association_data, subtree_hashes, references) + def construct_direct_append_updates(_association_data, subtree_hashes, references) ViewModel::ActiveRecord::UpdateData.parse_hashes(subtree_hashes, references) end