Last active
December 11, 2015 01:48
-
-
Save gbuesing/f19dd5d842a5b768b796 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Positioned | |
extend ActiveSupport::Concern | |
included do | |
before_save :set_position, unless: :position | |
end | |
module ClassMethods | |
def positioned | |
order(:position, :id) | |
end | |
def update_positions ids | |
transaction do | |
ids.each_with_index do |id, i| | |
position = i + 1 | |
where(id: id).update_all(position: position) | |
end | |
end | |
end | |
end | |
private | |
def set_position | |
self.position = Time.now.to_i # i.e., position new records at the bottom of the list | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment