From e0283c7824f897ffadcb4a64ccb9a09770395b7c Mon Sep 17 00:00:00 2001 From: Jordan Brough Date: Wed, 25 Jun 2014 11:57:40 -0600 Subject: [PATCH] fix for move_to_child_with_index method when moving a node downward (but not to the bottom) within its current parent the `move_to_child_with_index` method would insert the node in the wrong place. This is because when moving a node downward the positioning needs to take into account the fact that the moving node is being removed from its current position. also, add code to handle a no-op call -- moving a node to the position it's already at -- w/o raising an error. --- lib/awesome_nested_set/model/movable.rb | 12 +++++++++++- spec/awesome_nested_set_spec.rb | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/awesome_nested_set/model/movable.rb b/lib/awesome_nested_set/model/movable.rb index accd3890..1da5daf0 100644 --- a/lib/awesome_nested_set/model/movable.rb +++ b/lib/awesome_nested_set/model/movable.rb @@ -46,7 +46,17 @@ def move_to_child_with_index(node, index) elsif node.children.count == index move_to_right_of(node.children.last) else - move_to_left_of(node.children[index]) + my_position = node.children.index(self) + if my_position && my_position < index + # e.g. if self is at position 0 and we want to move self to position 1 then self + # needs to move to the *right* of the node at position 1. That's because the node + # that is currently at position 1 will be at position 0 after the move completes. + move_to_right_of(node.children[index]) + elsif my_position && my_position == index + # do nothing. already there. + else + move_to_left_of(node.children[index]) + end end end diff --git a/spec/awesome_nested_set_spec.rb b/spec/awesome_nested_set_spec.rb index 67e63d26..c1d93b1c 100644 --- a/spec/awesome_nested_set_spec.rb +++ b/spec/awesome_nested_set_spec.rb @@ -539,6 +539,23 @@ categories(:child_2).right.should == 7 end + it "move downward within current parent" do + categories(:child_1).move_to_child_with_index(categories(:top_level), 1) + categories(:child_1).parent_id.should == categories(:top_level).id + categories(:child_1).left.should == 6 + categories(:child_1).right.should == 7 + categories(:child_2).reload + categories(:child_2).parent_id.should == categories(:top_level).id + categories(:child_2).left.should == 2 + categories(:child_2).right.should == 5 + end + + it "move to the same position within current parent" do + categories(:child_1).move_to_child_with_index(categories(:top_level), 0) + categories(:child_1).parent_id.should == categories(:top_level).id + categories(:child_1).left.should == 2 + categories(:child_1).right.should == 3 + end end it "move_to_child_of_appends_to_end" do