diff --git a/app/models/domain/name_change_subdomains.rb b/app/models/domain/name_change_subdomains.rb index cb2e513..eb1bf28 100644 --- a/app/models/domain/name_change_subdomains.rb +++ b/app/models/domain/name_change_subdomains.rb @@ -5,10 +5,12 @@ class Domain < ActiveRecord::Base @apply_subdomains = ActiveRecord::ConnectionAdapters::Column.value_to_boolean(v) end + before_update do + self.parent = parent_domain if name_changed? # recompute parent + end + after_update do - if name_changed? - apply_subdomains ? chain_rename : sync_orphan_children - end + (apply_subdomains ? chain_rename : sync_orphan_children) if name_changed? end protected @@ -33,7 +35,7 @@ class Domain < ActiveRecord::Base # Syncs with nested interval when the parent is added later than the children def sync_orphan_children previous_children_subdomains.each do |subdomain| - subdomain.parent = nil + subdomain.parent = subdomain.parent_domain subdomain.save! end end diff --git a/app/models/domain/tree_structure.rb b/app/models/domain/tree_structure.rb index a9f6d4b..e1b6ba6 100644 --- a/app/models/domain/tree_structure.rb +++ b/app/models/domain/tree_structure.rb @@ -55,7 +55,16 @@ class Domain < ActiveRecord::Base set_callback :update, :before, :sync_children end + # Syncs with nested interval when a child is added and parent exists + def sync_parent + self.parent = parent_domain if !@parent_synced && new_parent? + end + protected + + def new_parent? + parent_domain.present? && self.parent_id != parent_domain.id + end # Returns the first immediate parent, if exists (does not cache the search) # For example "sub.sub.domain.com"'s parent might be "sub.domain.com" or "domain.com" @@ -79,13 +88,6 @@ class Domain < ActiveRecord::Base depth = first.depth descendants.select { |d| d.depth == depth } end - - # Syncs with nested interval when a child is added and parent exists - def sync_parent - if !@parent_synced && parent_domain.present? && self.parent_id != parent_domain.id - self.parent = parent_domain - end - end # Syncs with nested interval when the parent is added later than the children def sync_children diff --git a/spec/models/domain_spec.rb b/spec/models/domain_spec.rb index 5aea825..fb431fc 100644 --- a/spec/models/domain_spec.rb +++ b/spec/models/domain_spec.rb @@ -139,4 +139,14 @@ describe Domain do ss.parent.should_not be_nil end + it "recomputes parent", focus: true do + domain + subdomain + subsubdomain + subdomain.update_attributes(:name => "sub.changed#{domain.name}") + + subdomain.reload.parent.should be_nil + subsubdomain.reload.depth.should == 2 + end + end