Skip to main content

Rails i18n:Ruby on Rails 国际化完整指南

从第一个区域设置文件到生产环境:配置 Rails I18n、使用 t() 辅助函数、处理 CLDR 复数、修复常见问题,并添加智能区域设置回退链。

1

了解 Rails I18n 架构

Rails 内置 I18n gem。翻译文件以 YAML(默认)或 Ruby 文件形式存放在 config/locales/。框架在视图、控制器、模型和邮件程序中提供 t() 辅助函数(I18n.translate 的别名)。Rails I18n 设计简洁,开箱即用地处理基本翻译、插值和复数。

config/application.rb
# Rails includes i18n out of the box via the i18n gem
# config/application.rb
module MyApp
  class Application < Rails::Application
    # Default locale
    config.i18n.default_locale = :en

    # Available locales
    config.i18n.available_locales = [:en, :de, :ja, :es, :fr, :'pt-BR']

    # Fallback to default locale when translation is missing
    config.i18n.fallbacks = true

    # Load translations from nested directories
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
  end
end
config/routes.rb
# config/routes.rb
Rails.application.routes.draw do
  scope "/:locale", locale: /en|de|ja|es|fr|pt-BR/ do
    root "home#index"
    resources :products
  end

  root "home#index"
end

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  around_action :switch_locale

  private

  def switch_locale(&action)
    locale = params[:locale] || I18n.default_locale
    I18n.with_locale(locale, &action)
  end

  def default_url_options
    { locale: I18n.locale }
  end
end
Rails 会自动从 config/locales/ 加载所有 .yml 和 .rb 文件。您可以按语言(en.yml、de.yml)、按功能(en/users.yml、en/orders.yml)或同时采用两种方式(en/users.yml、de/users.yml)组织文件。Rails 在启动时合并所有文件。
2

配置区域设置

在 config/application.rb 或初始化程序中设置 default_locale、available_locales 和回退行为。在 ApplicationController 中使用 before_action 配置区域设置检测,从 URL、会话、Cookie 或 Accept-Language 标头设置区域设置。

config/locales/en.yml
# config/locales/en.yml
en:
  nav:
    home: "Home"
    about: "About"
    settings: "Settings"
  greeting: "Hello, %{name}!"
  cart:
    item_count:
      one: "%{count} item"
      other: "%{count} items"

# config/locales/de.yml
de:
  nav:
    home: "Startseite"
    about: "Über uns"
    settings: "Einstellungen"
  greeting: "Hallo, %{name}!"
  cart:
    item_count:
      one: "%{count} Artikel"
      other: "%{count} Artikel"
在 before_action 中设置 I18n.locale 对每个请求均安全,但在运行时设置 I18n.default_locale 是全局操作,会影响所有线程。请求范围内的区域设置更改应始终使用 I18n.locale(线程本地),切勿使用 I18n.default_locale。
3

使用 t() 辅助函数

t() 辅助函数可用于 Rails 的任何位置:视图、控制器、模型、邮件程序和作业。它接收键、可选插值变量,以及默认值和作用域等选项。在视图中,Rails 支持惰性查找,自动将键限定到当前控制器和操作。

app/views/example.html.erb
# In views (ERB)
<h1><%= t('nav.home') %></h1>
<p><%= t('greeting', name: @user.name) %></p>

# In controllers
flash[:notice] = t('flash.product_created')

# In models
validates :name, presence: { message: I18n.t('errors.blank') }

# With HTML (safe)
<%= t('terms_html', link: link_to(t('terms_link'), '/terms')) %>
4

处理复数

Rails I18n 使用 CLDR 复数类别:zero、one、two、few、many、other。英语只需要 one 和 other,其他语言则需要更多形式。将复数翻译定义为目标语言所需 count 类别下的嵌套 YAML 键。

Plural forms
# In YAML:
en:
  cart:
    item_count:
      zero: "No items"
      one: "%{count} item"
      other: "%{count} items"

# Arabic (6 forms):
ar:
  cart:
    item_count:
      zero: "لا عناصر"
      one: "عنصر واحد"
      two: "عنصران"
      few: "%{count} عناصر"
      many: "%{count} عنصرًا"
      other: "%{count} عنصر"

# Usage in views:
<%= t('cart.item_count', count: @cart.items.size) %>
如果当前区域设置缺少必需的复数类别,Rails 会引发 I18n::InvalidPluralizationData。如果俄语区域设置仅定义从英语复制的 one 和 other,数量 2、3、4 会导致崩溃,因为俄语需要 few 类别。请始终为每种语言定义所有 CLDR 类别。
5

添加区域设置回退链

Rails 内置的 I18n.fallbacks 只提供从地区区域设置到默认区域设置的基本回退。缺少某个键时,pt-BR 用户会看到英语,而不是 pt-PT。rails-locale-chain 添加可配置的深度合并链,使地区用户始终看到最接近的可用翻译。

Lazy lookups
# Lazy lookups use the controller/action as scope
# app/views/products/index.html.erb
# Instead of t('products.index.title'), just use:
<h1><%= t('.title') %></h1>
<p><%= t('.description') %></p>

# Rails looks up: products.index.title and products.index.description

# config/locales/en.yml
en:
  products:
    index:
      title: "All Products"
      description: "Browse our catalog"
rails-locale-chain 内置 75 条以上回退链,涵盖 11 个语系。将其添加到 Gemfile 并在初始化程序中配置,地区用户便会立即看到父级区域设置翻译,而不是英语缺口。
6

自动翻译

完成 Rails I18n 设置后,使用 AI 翻译 YAML 区域设置文件。i18n Agent 原生支持 YAML,将源区域设置文件交给它即可生成所有目标语言,并保留嵌套键、插值变量和复数形式。

config/initializers/locale_chain.rb
# Gemfile
gem 'rails-locale-chain'

# config/initializers/locale_chain.rb
Rails.application.config.i18n.fallbacks = {
  'pt-BR': ['pt', 'en'],
  'zh-Hant-TW': ['zh-Hant', 'zh', 'en'],
  'es-419': ['es', 'en'],
}

# The gem deep-merges translations across the chain
# pt-BR -> pt -> en
# Missing keys in pt-BR are filled from pt, then en
采用渐进式翻译——添加新键时,只翻译差异内容。这样可保留现有翻译,并避免重新生成未更改的字符串。

常见问题

InvalidPluralizationData 错误

缺少必需的 CLDR 复数类别时,Rails 会因 I18n::InvalidPluralizationData 崩溃。最常见的情况是将英语复数形式(one/other)复制到需要更多类别的语言(俄语需要 few,阿拉伯语需要 zero/two/few/many)。安装 rails-i18n 获取正确的 CLDR 规则,并定义所有类别。

在视图外使用惰性查找

惰性查找(t('.key'))仅适用于 Rails 了解控制器和操作的视图。在模型、邮件程序或服务对象中使用 t('.key') 会返回缺失翻译错误。请在视图外使用完整键(t('users.show.key'))。

YAML 语法错误导致所有翻译失效

一个 YAML 语法错误(缩进错误、特殊字符未加引号、使用制表符而非空格)就会阻止整个区域设置文件加载。该文件中的所有翻译都会返回缺失键错误。请在 CI 中使用检查工具验证 YAML 文件,并为包含冒号、方括号或前导特殊字符的字符串添加引号。

立即试用 i18n Agent

将翻译文件拖放到此处

JSON, YAML, PO, XML, CSV, Markdown, Properties

或点击选择文件

目标语言

无需注册即时估价

Rails i18n 常见问题