0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで日本語化および国際化機能をためす

Posted at

エラーメッセージの日本語化

デフォルトだと英語になっているので、日本語に変更する。

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) %>
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?