What is the best way to copy / clone the entire nested set from the root element down to the new tree

I am using "actions_as_nested_set" in my rails app. (extended with a great nested set of plugins). I was trying to logically distinguish a way to write a function / method to clone an element and its entire nested set, so that each element gets a clone, but the relationship structure mimics the original, only with new elements.

With nested sets, you get parent_id, lft, and rgt

positional columns ... instead of just position_id

.

Should I start at the bottom (nodes with no children) of each set and clone through the parents to the new root?

It looks like what has been done or that there will be a method to do this already for nested sets, but I can't see to find anything to help me.

thanks

0


a source to share


1 answer


I did something similar with actions like tree. I repeated the collective set and cloned each item. I saved the original element and the cloned element in a hash where the key was the source and clone the target. Then I used the hash along with the parent links to resolve and reassign the relationship.

Here's a snippet to help convey the message.



The clone method just creates a new copy with no ID. The descendants method returns the complete list of descendants, not just the immediate ones.

def clone_branch()
  h = {self => self.clone} #we start at the root

  ordered = self.descendants #preserved order with acts_as_sortable

  #clone subitems
  ordered.each do |item|
    h[item] = item.clone
  end

  #resolve relations
  ordered.each do |item|
    cloned = h[item]
    item_parent = h[item.parent]
    item_parent.children << cloned if item_parent
  end

  h[self]
end

      

+1


a source







All Articles