Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translations of column in same table

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.

like image 735
Sergei Struk Avatar asked Jul 04 '14 07:07

Sergei Struk


1 Answers

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.

like image 133
Dennis F. O'Connor Avatar answered Nov 15 '22 06:11

Dennis F. O'Connor