Column translations in one table

I have a small table:

create_table :cities do |t| t.string :name end 

I need to internationalize the "name" column, and I do not want to create a separate table for it. Can I add columns for translations to the "cities" table? As a result, I want the migration of this table to look like this:

 create_table :cities do |t| t.string :en_name t.string :de_name t.string :fr_name end 

I'm currently trying to use the "globalization" of the gem, maybe I should use some other solution for this, please advise.

+6
source share
1 answer

Standard practice is to use a translation table using gem globalization. If you do not want to use gem globalization, you can do the following:

 class City < ActiveRecord::Base AVAILABLE_LOCALES = [:en, :de, :fr] def name current_locale = I18n.locale if AVALIABLE_LOCALES.include? current_locale self.send("#{current_locale.to_s}_name") else #default language to use self.en_name end end end 

It just shows the access code (name function), you can also write a mutator (name = function) so that you can set the value based on the current locale. I18n.locale will provide you with the current locale.

+1
source

Source: https://habr.com/ru/post/971746/


All Articles