Created
March 28, 2018 16:17
-
-
Save cenan/c6129c8d0573dda60dd594c469dd00da to your computer and use it in GitHub Desktop.
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 Extensions::ActiveRecord::FindByOrderedIds | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def find_ordered(ids) | |
order_clause = "CASE id " | |
ids.each_with_index do |id, index| | |
order_clause << sanitize_sql_array(["WHEN ? THEN ? ", id, index]) | |
end | |
order_clause << sanitize_sql_array(["ELSE ? END", ids.length]) | |
where(id: ids).order(order_clause) | |
end | |
end | |
end | |
Students.find_ordered([2,4,1,3,5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment