Rails 3在生产模型中的翻译

我正在尝试将应用程序翻译成日语,一切顺利,直到我投入生产。

由于cache_classes现在为true,因此模型中的任何转换都将恢复为默认语言环境。

我知道我可能应该直接在yml文件中定位翻译,但我不确定如何为以下简化代码执行此操作:

class TimeseriesForecast  I18n.t('forecast_timeseries.location_name'), :local_date_time => I18n.t('forecast_timeseries.local_date_time'), :zulu_date_time => I18n.t('forecast_timeseries.zulu_date_time'), :temp_mean => I18n.t('forecast_timeseries.temp_mean') } end 

非常感谢

您在编译时计算了I18n.t()调用,因为您定义的是类变量,而不是实例变量。 您需要将您的调用发送到I18n.t,它们将在运行时进行评估。

但是,如果要翻译ActiveRecord字段名称,请使用human_attribute_name并通过YML提供翻译。 您无需手动提供翻译,Rails会自动为您处理。

相关文档位于http://guides.rubyonrails.org/i18n.html第5.1章。

不要在模型中使用I18n.t或translate方法。 你可以这样做:

在你的模型中

使用类似的东西将国际化错误添加到模型的name属性中(检查文档: ActiveModel / Errors / method-i-add ):

 self.errors.add(:name, :your_error_key) # The error key could be something like :wrong_name 

注意:有时您甚至不需要使用errors.add方法添加错误。 例如,如果您在模型中添加validation,如下所示:

 validates :name, presence: true 

Rails将使用密钥添加错误:blank (密钥取决于validation类型)。 换句话说,rails内部将发出self.errors.add(:name, :blank)

在您的语言环境中

然后在你的locale.jp.yml中可以使用任何一个(只有一个):

 activerecord.errors.models.[model_name].attributes.[attribute_name] activerecord.errors.models.[model_name] activerecord.errors.messages errors.attributes.[attribute_name] errors.messages 

在您的情况下,使用timeseries_forecast替换[model_name] your_error_key [attribute_name]使用your_error_key替换[attribute_name]

例如:

 en: errors: messages: your_error_key: "Your error message in english" 

不要以为通过缓存类中的名称来提高性能。 把它变成一种方法。

 class TimeseriesForecast < ActiveRecord::Base def self.field_names { :location_name => I18n.t('forecast_timeseries.location_name'), :local_date_time => I18n.t('forecast_timeseries.local_date_time'), :zulu_date_time => I18n.t('forecast_timeseries.zulu_date_time'), :temp_mean => I18n.t('forecast_timeseries.temp_mean') } end end # usage TimeseriesForecast.field_names 

更好的是,只返回实际字段并在视图中进行翻译,如果你要对它进行严格的MVC(一些Rails方法 – 比如collection_select – 尽管这样做更难,因此上面的建议)。