• 不应在视图、模型或控制器里添加语言相关的设置,应在 config/locales 目录下进行设置。

    • 当 ActiveRecord 模型的标签需要被翻译时,应使用activerecord scope:

      1. en:
      2. activerecord:
      3. models:
      4. user: Member
      5. attributes:
      6. user:
      7. name: "Full name"

      然后 User.model_name.human 会返回 “Member” ,而 User.human_attribute_name("name") 会返回 “Full name”。这些属性的翻译会作为视图中的标签。

    • 把在视图中使用的文字与 ActiveRecord 的属性翻译分开。把模型使用的语言文件放在 models 目录下,把视图使用的文字放在 views 目录下。

      • 当使用额外目录来设置语言文件时,应在 application.rb 文件里列出这些目录以加载设置。

        1. # config/application.rb
        2. config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
    • 把共享的本地化选项,如日期或货币格式,放在 locales 的根目录下。

    • 应使用精简形式的 I18n 方法:
      使用 I18n.t 而非 I18n.translate
      使用 I18n.l 而非 I18n.localize

    • 应使用 “懒惰” 查询来获取视图中使用的文本。假设我们有以下结构:

      1. en:
      2. users:
      3. show:
      4. title: "User details page"

      users.show.title 的数值能这样被 app/views/users/show.html.haml 获取:

      1. = t '.title'
    • 应在控制器与模型中使用点分隔的键,而非指定 :scope 选项。点分隔的调用更容易阅读,也更易追踪层级关系。

      1. # 差
      2. I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages]
      3. # 好
      4. I18n.t 'activerecord.errors.messages.record_invalid'
    • 更详细的 Rails i18n 信息可以在 Rails Guides 找到。