
Rails i18n:Ruby on Rails 国際化完全ガイド
最初のロケールファイルから本番環境まで。Rails I18n の設定、t() ヘルパー、CLDR 複数形処理、よくある問題の修正、スマートなロケールフォールバックチェーンを解説します。
Rails I18n のアーキテクチャを理解する
Rails には I18n gem が組み込まれています。翻訳ファイルは config/locales/ に置き、YAML(標準)または Ruby ファイルを使用します。ビュー、コントローラー、モデル、メーラーで t() ヘルパー(I18n.translate の別名)を利用できます。Rails I18n は意図的にシンプルに設計されており、基本的な翻訳、補間、複数形処理に標準で対応します。
# 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
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ロケール設定
config/application.rb または初期化ファイルで、default_locale、available_locales、フォールバック動作を設定します。ApplicationController で before_action を使用し、URL、セッション、Cookie、Accept-Language ヘッダーからロケールを取得して設定するよう構成します。
# 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"t() ヘルパーの使用
t() ヘルパーは、ビュー、コントローラー、モデル、メーラー、ジョブなど、Rails のどこからでも利用できます。キー、任意の補間変数、デフォルト値やスコープなどのオプションを受け取ります。ビューでは、現在のコントローラーとアクションにキーを自動でスコープする遅延検索に対応します。
# 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')) %>複数形の処理
Rails I18n は、zero、one、two、few、many、other の CLDR 複数形カテゴリを使用します。英語で必要なのは one と other だけですが、他の言語ではさらに多くの形式が必要です。対象言語で必要な複数形カテゴリの下に、複数形の翻訳を YAML のネストキーとして定義します。
# 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.fallbacks は、地域ロケールからデフォルトロケールへの基本的なフォールバックしか提供しません。そのため、pt-BR でキーが欠落すると pt-PT ではなく英語が表示されます。rails-locale-chain は構成可能なディープマージチェーンを追加し、地域別ロケールのユーザーに利用可能な最も近い翻訳を表示します。
# 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 I18n の設定が完了したら、AI で YAML ロケールファイルを翻訳します。i18n Agent は YAML を標準でサポートします。翻訳元ロケールファイルを指定すれば、ネストキー、補間変数、複数形式を保持しながら、すべての対象言語の翻訳ファイルを生成します。
# 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 エラー
ビュー外での遅延検索
YAML 構文エラーですべての翻訳が読み込めない
i18n Agent を今すぐ試す
翻訳ファイルをここにドロップ
JSON, YAML, PO, XML, CSV, Markdown, Properties
またはクリックしてファイルを選択
翻訳先言語