ruby-on-railsmobility

Limit results scope for translations to current locale only with Mobility


How do I limit the result set of a query to records that have a translation for the current locale (or fallback) while leaving out any records that don't?

For example, given a locale of :fr, I only want Article.all to return only articles that have a French translation. Same with :'fr-FR'—I want to return any record that has a translation locale of :'fr-FR' or :fr, but nothing else.

Article.joins(:translations).where(article_translations: { locale: [I81n.locale] }) works for a single location, but what about fallbacks?


Solution

  • There is no backend-agnostic way to do this (currently). This issue would be one step toward implementing it.

    However, with the table backend, when you call join_translations, you're using an inner join, so only records with a translations model in the current locale will be joined, and any articles without any translations in the current locale will not be returned. So just Ariticle.i18n.join_translations will weed out any articles that don't have translations in the current locale, without doing anything else.

    However, this won't include fallbacks currently. For that, you'll have to either figure out the SQL yourself, or wait until the feature is implemented (probably not for a few months at least).