Last active
October 20, 2017 18:11
-
-
Save bbagno/322ce3f548998596d5706f6579a0d9f1 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
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
# Universal replacement for MySQL's ORDER BY FIELD(name, •values) | |
def self.order_by_field(field, values) | |
ordering_table_id = SecureRandom.urlsafe_base64 | |
ordering_table_rows = values.map.with_index { |value, index| "(#{value},#{index + 1})" } | |
joins( | |
<<-SQL | |
INNER JOIN (VALUES #{ordering_table_rows.join(',')}) AS "ordering_table_#{ordering_table_id}" ("#{field}", "ordering") | |
ON "#{table_name}"."#{field}" = "ordering_table_#{ordering_table_id}"."#{field}" | |
SQL | |
).order("\"ordering_table_#{ordering_table_id}\".\"ordering\"") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment