krunal shah
krunal shah

Reputation: 16339

Deletion of a parent node but not the children with awesome_nested_set?

Deletion of a parent node but not the children.

The child nodes should all be moved up to the level of the deleted parent.

How can I handle this scenario with awesome_nested_set plug in ?

EDIT

Before child deleted

Id , Title, lft, rgt, parent_id

1, root, 7, 12, nil

2, child, 8, 11, 1

3, sub child, 9, 10, 2

After deleted 2 record

Id , Title, lft, rgt, parent_id

1, root, 7, 12, nil

3, sub child, 9, 10, 1

I want to move sub child to immediate parent of deleted object. Is this a proper result ? Or lft and rgt should be change after delete ?

Upvotes: 2

Views: 871

Answers (2)

krunal shah
krunal shah

Reputation: 16339

Controller

  @node = Node.find(params[:id])
  @node.delete_node_keep_sub_nodes
  @node.reload
  @node.destroy

Model

  def delete_node_keep_sub_nodes
    if self.child?
      self.move_children_to_immediate_parent
    else
      self.move_children_to_root
    end
  end

  def move_children_to_immediate_parent
    node_immediate_children = self.children
    node_immediate_parent = self.parent
    node_immediate_children.each do |child|
      child.move_to_child_of(node_immediate_parent)
      node_immediate_parent.reload
    end
  end

  def move_children_to_root
    node_immediate_children = self.children
    node_immediate_children.each do |child|
      child.move_to_root
      child.reload
    end
  end

Upvotes: 3

fl00r
fl00r

Reputation: 83680

Some kind of this:

  • Find parent of deleted node
  • Move all children to new parent

Example

@node = Node.find(params[:id])
@children = @node.children
@parent = @node.parent
@children.each{ |child| child.move_to_child_of @parent }

Upvotes: 1

Related Questions