【问题标题】:Rails 3 translations within models in production生产模型中的 Rails 3 翻译
【发布时间】:2011-10-28 01:45:46
【问题描述】:

我正在尝试将一个应用程序翻译成日语,在我将它投入生产之前一切都很顺利。

由于 cache_classes 现在为 true,模型中的任何翻译都会恢复到默认语言环境。

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

class TimeseriesForecast < ActiveRecord::Base

  @@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

非常感谢

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 localization internationalization


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      不要在模型中使用 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 方法添加错误。例如,如果您使用以下方式在模型中添加验证:

      validates :name, presence: true
      

      Rails 将使用键 :blank 添加错误(该键取决于验证类型)。换句话说,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
      

      在您的情况下,将[model_name] 替换为timeseries_forecast,将[attribute_name] 替换为your_error_key

      例如:

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

      【讨论】:

        【解决方案3】:

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

        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 - 虽然这样做更难,因此建议以上)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-25
          • 2011-05-17
          相关资源
          最近更新 更多