Rails Kitchen

It's a place to write on stuff I learned recently.

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

| Comments

The Ruby I18n gem which is shipped with Ruby on Rails provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or for providing multi-language support in your application.

To translate model Project to another language (for example, to arabic), add model name in arabic with key one and pluralal of model name in arabic with key other in to config/locales/ar.yml.
1
2
3
4
5
6
7
8
9
10
11
12
13
ar:
  activerecord:
    models:
      project:
        one: مشروع
        other: مشاريع
      task:
  one: مهمة
        other: المهام   
    attributes:
      project: 
        title: لقب
        # will translate Project attribute "title" as "لقب"
that’s it, now if you switch your application to Arabic you can see everywhere in the project is translated into مشروع and projects is translate into مشاريع. Project attribute title will be translated into لقبs.

Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations.

Consider a Project model with a validation for the title attribute like this:
1
2
3
class Project < ActiveRecord::Base
  validates :title, presence: true
end
The key for the error message in this case is :blank. So add message to be shown in following order to ar.yml
1
2
3
4
5
6
7
activerecord:
    errors:
      models:
        project:
          attributes:
            title:
              blank : لا يمكن أن يكون البنك
For more details check official rails guides

Comments