6

我有小桌子:

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

我需要国际化“名称”列,我不想为此创建单独的表。是否可以将翻译列添加到“城市”表?结果,我希望该表的迁移如下所示:

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

目前我正在尝试使用“全球化”gem,也许我应该为此使用其他解决方案,请告知。

4

1 回答 1

1

标准做法是使用带有 globalize gem 的翻译表。如果您不想使用 globalize gem,可以执行以下操作:

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

这只是显示访问器的代码(name 函数),您可能还想编写一个 mutator(a name= function),以便您可以根据当前语言环境设置值。I18n.locale 将为您提供当前的语言环境。

于 2014-08-01T13:23:04.240 回答