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