Globalize3 order records by translated attributes and taking fallbacks into consideration

随声附和 提交于 2019-12-23 12:35:34

问题


Im having troubles with awesome Globalize3 gem. For now I`m having two languages :en and :ru. And :ru falls back to :en like this

#/config/initializers/globalize.rb
Globalize.fallbacks = {:ru => [:ru, :en]}

In my controller I am trying to sort the whole collection of translated records either by name translations or by translations fallback values. But with_translations() does not seem to give me such opportunity!

Country.with_translations(:ru).order('country_translations.name ASC')
#this filters out those who have no :ru translations (BUT THEY SHOLD USE FALLBACKS!)

so to retrieve all records i can pass an array of locales:

Country.with_translations([:ru, :en]).order('country_translations.name ASC')
#but this completely ruins the sorting order (DAMN NOTHING IS SORTED)

and the only simple thing i want is to get fallbacks and sorting all togather! So we need somehow get all records only sorted by available name value.

Is there any way?


回答1:


Solved this by digging into Globalize3 source. It uses with_locales scope to get records that have proper locales present. I just needed them all:

Model.includes(:translations).
       with_locales(I18n.available_locales).
       order('model_translations.name ASC')

Hope it will help someone!




回答2:


Would have left this as a comment, but don't have the reputation yet, so figured I might as well leave this as an answer.

  1. In Rails 4, that query as it is currently written throws a long deprecation warning about implicit joins (which is what you're doing by referencing the model_translations table in the where cause).

  2. I believe you are trying return Model records, not Model::Translation records. As such, I think you can swap the includes for a join, which should be more performant and gets rid of the deprecation warning.

In my Rails 4 app, the join worked perfectly, but I haven't tested it in Rails 3.



来源:https://stackoverflow.com/questions/16041392/globalize3-order-records-by-translated-attributes-and-taking-fallbacks-into-cons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!