Created
August 11, 2014 17:19
-
-
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
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
# 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 |
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
# 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