Skip to content

Instantly share code, notes, and snippets.

@cenan
Created March 28, 2018 16:17
Show Gist options
  • Save cenan/c6129c8d0573dda60dd594c469dd00da to your computer and use it in GitHub Desktop.
Save cenan/c6129c8d0573dda60dd594c469dd00da to your computer and use it in GitHub Desktop.
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