Skip to content

Instantly share code, notes, and snippets.

@bbagno
Last active October 20, 2017 18:11
Show Gist options
  • Save bbagno/322ce3f548998596d5706f6579a0d9f1 to your computer and use it in GitHub Desktop.
Save bbagno/322ce3f548998596d5706f6579a0d9f1 to your computer and use it in GitHub Desktop.
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