LoginSignup
3
2

More than 5 years have passed since last update.

railsのi18n使い方

Posted at

1. 設定ファイル読み込み

config/initializes/i18n.rb
# encoding: utf-8
I18n.default_locale = 'ja'
LOCALES_DIRECTORY = "#{Rails.root}/config/locales/"
LOCALES_AVAILABLE = Dir["#{LOCALES_DIRECTORY}/*.{rb,yml}"].map do |locale_file|
  File.basename(File.basename(locale_file, '.rb'), '.yml')
end.uniq.sort

2.使う

config/locales/ja.yml
ja:
  activerecord:
    models: &models
      user: "ユーザー"
    attributes: &attributes
      user:
        name: ”名前”

とした場合、

$ I18n.t('activerecord.models.user')
=> "ユーザー"  
$ I18n.t('activerecord.attributes.user.name')
=> "名前"  

と使用できる

viewで使う

sample.html.erb
<div>
  <%= t('activerecord.attributes.user.name') %> #”名前”  
</div>

ドキュメント

https://railsguides.jp/i18n.html
https://qiita.com/Kta-M/items/bd4ba36a58ad602a9d8b

3
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
3
2