Reputation: 358
I have small table:
create_table :cities do |t|
t.string :name
end
I need to internationalize "name" column and I don't want create separate table for this. Is it possible to add columns for translations to "cities" table? In result I want that migration of this table looks like this:
create_table :cities do |t|
t.string :en_name
t.string :de_name
t.string :fr_name
end
Currently I'm trying to use "globalize" gem, maybe I should use some other solution for this, please, advise.
Upvotes: 6
Views: 451
Reputation: 571
The standard practice is to use the translation table with the globalize gem. If you don't want to use the globalize gem, 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
This just shows the code for the accessor(the name function), you may also want to write a mutator(a name= function) so you can set the value based on the current locale. I18n.locale will provide you with the current locale.
Upvotes: 1