From 31b73171dc95b1e6ac506ef9dd383c197c42d06b Mon Sep 17 00:00:00 2001 From: Sam <sam.saffron@gmail.com> Date: Mon, 21 Oct 2013 16:14:09 +1100 Subject: [PATCH] correct ordering algorithm --- lib/concern/positionable.rb | 6 ++++++ spec/components/concern/positionable_spec.rb | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/concern/positionable.rb b/lib/concern/positionable.rb index 6a7c69060ea..ec97a4442dc 100644 --- a/lib/concern/positionable.rb +++ b/lib/concern/positionable.rb @@ -9,6 +9,12 @@ module Concern 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 diff --git a/spec/components/concern/positionable_spec.rb b/spec/components/concern/positionable_spec.rb index 32b2d4b0469..fa8c3f8b151 100644 --- a/spec/components/concern/positionable_spec.rb +++ b/spec/components/concern/positionable_spec.rb @@ -34,11 +34,13 @@ describe Concern::Positionable do 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]