Created
November 15, 2014 22:30
-
-
Save typeoneerror/c2814867a9bceedbe11e to your computer and use it in GitHub Desktop.
Concern for PostgreSQL sort records by ID in one query
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 DokiCore | |
module Concerns | |
module Sortable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# Run a "single" query to update multiple records by position. | |
# | |
# The Array of passed in IDs are sorted in the order they are | |
# provided in the array. | |
# | |
# @param [Array] ids IDs of records to sort | |
# | |
def sort_all_by(ids) | |
ids = Array(ids) | |
records = self.where({ id: ids }) | |
records.update_all([ | |
"position = (STRPOS(?, ','||lpad(cast(id as text), 20, '0')||',') - 1)/21 + 1", | |
",#{ids.map{|x| "%020d" % x }.join(',')}," | |
]) | |
records | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment