Skip to content

Instantly share code, notes, and snippets.

@rurabe
Last active August 29, 2015 14:22
Show Gist options
  • Save rurabe/6c869ee1a3386c803b40 to your computer and use it in GitHub Desktop.
Save rurabe/6c869ee1a3386c803b40 to your computer and use it in GitHub Desktop.
Reorder as a concern
module IsOrderable
extend ActiveRecord::Concern
def change_position_to(n)
safe_n = self.class.sanitize(n)
current_position = self.class.sanitize(position)
connection.execute(<<-SQL
BEGIN;
UPDATE #{self.class.table_name} SET position = position + 1 WHERE parent_id = #{parent_id} AND position < #{current_position} AND position >= #{safe_n};
UPDATE #{self.class.table_name} SET position = position - 1 WHERE parent_id = #{parent_id} AND position > #{current_position} AND position <= #{safe_n};
UPDATE #{self.class.table_name} SET position = #{safe_n} WHERE id = #{id};
COMMIT;
SQL)
end
end
class Foo < ActiveRecord::Base
include IsOrderable
end
Foo.find(id).change_position_to(4)
Foo.order(position: :asc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment