【问题标题】:Translations of column in same table同一张表中列的翻译
【发布时间】:2014-08-25 10:49:03
【问题描述】:

我有一张小桌子:

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,也许我应该为此使用其他解决方案,请告知。

【问题讨论】:

  • 你可以试试参考这个answer

标签: ruby-on-rails internationalization rails-i18n globalize3 globalize


【解决方案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 将为您提供当前的语言环境。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 2017-02-14
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多