Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Created August 11, 2014 17:19
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 chrisbloom7/f229a548513a93f594f4 to your computer and use it in GitHub Desktop.
Save chrisbloom7/f229a548513a93f594f4 to your computer and use it in GitHub Desktop.
Rails ActiveRecord finder that accepts an array of IDs and preserves the order in the results
# config/initializers/active_record.rb
module ActiveRecord
class Base
# Find by array of IDs, preserving order of IDs
# See http://stackoverflow.com/a/25248122/83743
def self.find_with_relevance(array_of_ids)
array_of_ids = Array(array_of_ids) unless array_of_ids.is_a?(Array)
self.find(array_of_ids).index_by(&:id).slice(*array_of_ids).values
end
end
end
# config/initializers/enumerable.rb
# This is necessary in Rails <= 2.3
module Enumerable
def index_by_with_ordered_hash
inject(ActiveSupport::OrderedHash.new) do |accum, elem|
accum[yield(elem)] = elem
accum
end
end
alias_method_chain :index_by, :ordered_hash
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment