Skip to content

Instantly share code, notes, and snippets.

@RafeHatfield
Last active August 29, 2015 13:57
Show Gist options
  • Save RafeHatfield/9623316 to your computer and use it in GitHub Desktop.
Save RafeHatfield/9623316 to your computer and use it in GitHub Desktop.
Sort Active Record collection by an ordered list of id's
# Small method to re-sort a result from ActiveRecord by a pre-ordered list of id's.
# Method is of great use e.g. when using Redis to store sorted sets and needing to
# retrieve those objects, preserving the order.
# The method makes one query to retrieve the records, then uses index_by to create
# a hash of the result for fast resorting.
# Future enhancements should allow for extra params to be passed in, such as a list
# of other models to include and prevent n+1 queries, possibly the ability to pass
# in a model method for the query to use in place of 'where' if required, and possibly
# the ability to add extra ActiveRecord parameters to the query.
module ActiveRecordSorter
def retrieve_ar_and_sort_by_id_list(klass, sorted_id_set)
unsorted_klass = klass.constantize.where(id: sorted_id_set)
klass_index = unsorted_klass.index_by &:id
sorted_klass = sorted_id_set.map{|id| klass_index[id.to_i]}.compact
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment