Last active
August 29, 2015 14:22
-
-
Save rurabe/6c869ee1a3386c803b40 to your computer and use it in GitHub Desktop.
Reorder as a concern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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