【问题标题】:What is the way to add translation to an array?向数组添加翻译的方法是什么?
【发布时间】:2012-04-18 19:10:11
【问题描述】:
对不起,如果这真的很容易。但是我尝试了很多方法来添加 I18n,但似乎都不起作用。
这是风景
= @event.categories.map(&:name).to_sentence
这是在语言环境中
#Categories
categories:
gastronomy: Gastronomy
family: Family
sports: Sports
scene: Scene
traditional: Tradition
music: Music
party: Party
我设法让翻译工作在表格中,但不是在这里。知道为什么吗?
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3.1
internationalization
activesupport
【解决方案1】:
选项 1
假设有如下yaml文件结构
categories:
gastronomy: Gastronomy
family: Family
sports: Sports
scene: Scene
traditional: Tradition
music: Music
party: Party
现在您可以执行以下操作:
@event.categories.map{|n| I18n.t("categories.#{n}"}.to_sentence
选项 2
更好的是,您可以更改 Category 模型以返回本地化名称:
class Category < ActiveRecord::Base
def name
key = read_attribute(:name)
return key if key.blank? # return immediately if nil
# use the key as value if the localization value is missing
I18.n("categories.#{key}", :default => key.humanize)
end
end
现在,name 方法返回一个本地化值:
cat.name # localized name
您的原始陈述也可以使用
@event.categories.map(&:name).to_sentence
选项 3
使用Globalize3 宝石。观看此screencast 了解更多详情。