SoFunction
Updated on 2025-04-07

A brief discussion on the internationalization of Ruby on Rails

Language-related settings and strings should not be used in views, models and controllers. These texts should be moved to the language file under config/locales.

When the tags of the ActiveRecord model need to be translated, use the activecord scope:

en:
 activerecord:
  models:
   user: Member
  attributes:
   user:
    name: "Full name"

Then User.model_name.human will return "Member" and User.human_attribute_name("name") will return "Full name". Translations of these properties are used by the view as a tag.

Separate the text used in the view from the property translation of ActiveRecord. Place the language file used for the model in a folder named models, and the text used for the view in a folder named views.

When the language file organization using additional directories is completed, in order to load these directories, the directories must be described in the file.

  # config/
  config.i18n.load_path += Dir[('config', 'locales', '**', '*.{rb,yml}')]

Place shared localization options, such as date or currency formats, in the root directory of locales.

Use the thin form of I18n method: to replace and use substitute.

Use Lazy to query the text used in the view. Suppose we have the following structure:

en:
 users:
  show:
   title: "User details page"

The value can be queried by app/views/users/ like this:

= t '.title'

The controller uses a point-separated key to replace the :scope option specified. Point-separated calls are easier to read and track levels.

# Call this '.record_invalid'

# Instead of this :record_invalid, :scope => [:activerecord, :errors, :messages]