Skip to content

Instantly share code, notes, and snippets.

@gbuesing
Last active December 11, 2015 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbuesing/f19dd5d842a5b768b796 to your computer and use it in GitHub Desktop.
Save gbuesing/f19dd5d842a5b768b796 to your computer and use it in GitHub Desktop.
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