Translations of column in same table
Asked Answered
C

1

6

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.

Cracksman answered 4/7, 2014 at 7:6 Comment(1)
You can try to refer to this answerIslamize
J
1

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.

Jeremy answered 1/8, 2014 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.