Skip to content

Commit

Permalink
correct ordering algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
SamSaffron committed Oct 21, 2013
1 parent 29c8d2e commit 31b7317
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/concern/positionable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ module Positionable
end

def move_to(position)

self.exec_sql "
UPDATE #{self.class.table_name}
SET position = position - 1
WHERE position > :position AND position > 0", {position: self.position}

self.exec_sql "
UPDATE #{self.class.table_name}
SET position = :position
Expand Down
4 changes: 3 additions & 1 deletion spec/components/concern/positionable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ class TestItem < ActiveRecord::Base
positions.should == [3,0,1,2,4]
TestItem.pluck(:position).sort.should == [0,1,2,3,4]

TestItem.find(3).move_to(1)
positions.should == [0,3,1,2,4]

# this is somewhat odd, but when there is not positioning
# not much we can do
TestItem.find(1).move_to(5)
positions.should == [3,0,2,4,1]
positions.should == [0,3,2,4,1]

TestItem.pluck(:position).sort.should == [0,1,2,3,4]

Expand Down

0 comments on commit 31b7317

Please sign in to comment.