Skip to content

Instantly share code, notes, and snippets.

@daniel-rikowski
Created May 26, 2016 13:18
Show Gist options
  • Save daniel-rikowski/1d94ea943bbcf8935fd0f23a5c8b37f6 to your computer and use it in GitHub Desktop.
Save daniel-rikowski/1d94ea943bbcf8935fd0f23a5c8b37f6 to your computer and use it in GitHub Desktop.
Rails model concern to support ordering of hstore_translated attributes with fallbacks
# frozen_string_literal: true
module OrderByTranslated
extend ActiveSupport::Concern
module ClassMethods
def order_translated(*attributes)
order(order_translated_sql(nil, *attributes))
end
def reorder_translated(*attributes)
reorder(order_translated_sql(nil, *attributes))
end
private
def order_translated_sql(table_prefix, *attributes)
table_prefix ||= table_name
attributes.map do |attribute|
unless attribute.is_a?(Hash)
attribute = { attribute => :asc }
end
attribute.map do |attr, direction|
if %w(asc desc).include?(direction.to_s)
full_attribute = table_prefix.present? ? "#{table_prefix}.#{attr}" : attr
fields = I18n.fallbacks[I18n.locale].map { |locale| "#{full_attribute}_translations->'#{locale}'" }
"coalesce(#{fields.join(', ')}) #{direction}"
else
order_translated_sql(attr.to_s, direction)
end
end
end.flatten.join(', ')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment