What is the recommended approach for maintaining multilingual values in the ActiveRecord model.
I am studying the modernization of our database schema and object models to ensure the wide internationalization of many values, and I am weighing various ways to do this.
The standard rails-i18n system is largely silent about this, although it offers powerful tools for internationalizing field names and models, in addition to text in views.
The R18n gem allows you to overload your database with columns that store localized strings and that represent the correct value depending on the locale. This is a couple of problems.
Let's say we are talking about a model Sport- a database table sports. We need to be able to search Sport.where(name: 'soccer'), although in the UK they are called "football", so the request becomes scope :with_name ->(n){ where("name_en_GB = ? OR name_en_AU = ?", n, n) }.
If we want to add another language standard, we need to both update the scheme and update any such requests on this scheme. Pretty fragile solution.
Another solution I've seen is to support a separate model SportLocaleand its associated table sport_locales, which contains the name and locale.
Assuming
class Sport < ActiveRecord::Base
has_many :locales
end
class SportLocale < ActiveRecord::Base
belongs_to :sport
end
Then, to find the right sport, you would do something like
class Sport < ActiveRecord::Base
has_many :locales, class_name: "SportLocale"
self.with_name(n)
SportLocale.where(name: n, locale: I18n.locale).first.try(:sport)
end
end
, Sport - , , , * Locale. DRY est.
,
class Sport < ActiveRecord::Base
include Localised
localised_field :name
end
Sport.where(name: 'football') .
, ?
?