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 常見問題