Published on
1 min read

Translate Active Record Model Name, Attributes, and Error Messages with Rails Internationalization (I18n) API

Authors

The Ruby I18n gem shipped with Rails provides an extensible framework for providing multi-language support.

To translate the Project model to Arabic, add the following to config/locales/ar.yml:

ar:
  activerecord:
    models:
      project:
        one: مشروع
        other: مشاريع
      task:
        one: مهمة
        other: المهام
    attributes:
      project:
        title: لقب

Now, your application will correctly use مشروع for Project and لقب for its title attribute when the locale is set to Arabic.

Translating Validation Messages

Active Record validation error messages can also be translated. Consider a Project model:

class Project < ActiveRecord::Base
  validates :title, presence: true
end

The key for the presence validation error is :blank. Add the following to your ar.yml:

ar:
  activerecord:
    errors:
      models:
        project:
          attributes:
            title:
              blank: 'لا يمكن أن يكون فارغاً'

For more details, check out the Official Rails Guide on I18n.

TwitterLinkedInHacker News