エラーメッセージの日本語化
デフォルトだと英語になっているので、日本語に変更する。
config/application.rb
(中略)
config.generators.system_tests = nil
config.time_zone = "Tokyo"
# ↓これを追加
config.i18n.default_locale = :ja
config配下のファイルは自動更新されないので、変更後は必ずサーバーを再起動する。
次にgemパッケージ「rails-i18n」を追加する。
Gemfile
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
gem 'email_validator', '~> 1.6'
# 以下を追加
gem 'rails-i18n', '~> 5.1'
bundle install
これでエラー時に表示される、「can't be blank」部分は日本語化できる。
しかし、モデルの情報については英語のままになるので、それについても対応が必要。
config/locales/ja.yml
ja:
activerecord:
models:
member: 会員情報
attributes:
member:
number: 背番号
name: ユーザー名
full_name: 氏名
sex: 性別
sex_1: 男
sex_2: 女
birthday: 誕生日
email: メールアドレス
administrator: 管理者
これでモデル情報についても日本語化される。
Railsの国際化機能の使い方
ロケールテキストを読みだすには、I18nクラスのtranslateメソッド(t)を使う。
また、日付や時刻を現在のロケールに従った、文字列に変換するには、localizeメソッド(l)を使う。
viewやcontrollerで使う場合は、I18nを省略して書くことができる。
ロケールの設定がjaならja:の下のテキストが使われる。
config/locales/ja.yml
ja:
messages:
hello: "%{name}さん、こんにちは"
date:
formats:
default: "%Y/%m/%d"
long: "%Y年%m月%d日(%a)"
short: "%m/%d"
time:
am: 午前
formats:
default: "%Y/%m/%d %H:%M:%S"
long: "%Y年%m月%d日(%a) %H時%M分%S秒"
short: "%y/%m/%d %H:%M"
pm: 午後
a = I18n.t("messages.hello", name: "プーさん")
s = I18n.l(Time.current)
指定した国際化フォーマットを使った例
sample.erb
<%= t("messages.hello", name: "プーさん") %>
<%= l(Time.current, format: :long) %>