Add method to retrieve translations in one database query

This methods performs much better when we need to load a lot of
globalized models translations and returns the best fallback translation
for the current language.
This commit is contained in:
Senén Rodero Rodríguez
2023-05-24 16:29:05 +02:00
parent cf8a98f06b
commit 2b0a812543
2 changed files with 77 additions and 5 deletions

View File

@@ -100,5 +100,22 @@ module Globalizable
def translation_class_delegate(method)
translation_class.instance_eval { delegate method, to: :globalized_model }
end
def with_fallback_translation
translations_foreign_key = reflect_on_association(:translations).foreign_key
fallbacks = Globalize.fallbacks(Globalize.locale)
fallbacks_with_order = fallbacks.map.with_index do |locale, order|
"('#{locale}', #{order})"
end.join(", ")
translations_ids = translation_class
.select("DISTINCT ON (#{translations_foreign_key}) id")
.where(locale: fallbacks)
.joins("LEFT JOIN (VALUES #{fallbacks_with_order}) AS locales(name, ordering) ON locale = locales.name")
.order(translations_foreign_key, "locales.ordering")
with_translations(fallbacks).where("#{translations_table_name}.id": translations_ids)
end
end
end