[Ruby] Japanese localization using i18n with Rails

1 minute read

  • Environment: ruby 2.5.1 / rails 5.2.3*

Thing you want to do

  • I want to replace Japanese parts such as error messages in English
  • When displaying DB column name or class attribute, I want to display the one that has been replaced in Japanese in advance

Conclusion

  • Introduce grail rails-i18n
  • Set the words you want to convert in the ja.yml file

way

  • Introduce grail rails-i18n

Gemfile


# Place it at the bottom of the file or in a place other than group :development, group :development, :test
gem'rails-i18n'
  • install gem
  • Change the default locale in config/application.rb to ja

application.rb


# ↑ The code above this is omitted
module App
  class Application <Rails::Application
    config.i18n.default_locale = :ja
    config.time_zone ='Tokyo'
  end
end
  • Create a file of config/locales/ja.yml
  • In ja.yml, describe the settings you want to convert to Japanese in yml format
    Example: DB column characters → activerecord: attributes: Model name:
    Characters related to view → views: resource name:

ja.yml


ja:
  activerecord:
    attributes:
      user:
        name: user name
        email: Email
        password: password
        password_confirmation: Password (confirmation)
      tweet:
        name: name
        title: title
        body: Body
      comment:
        name: name
        comment: comment
  views:
    pagination:
      first: first
      last: last
      previous: previous
      next: Next
      truncate: ...
  • After setting, restart the server (because it is not reflected unless you do this)