Rails I18n scope for humanized attribute names

Posted . Visible to the public. Repeats.

ActiveModel classes have a class method .human_attribute_name. This returns a human-readable form of the attribute:

Person.human_attribute_name(:first_name) # => "First name"

By default Rails will use String#humanize Show archive.org snapshot to format the attribute name, e.g. by replacing underscores with spaces and capitalizing the first word. You can configure different translation in your I18n locales, e.g. in config/locales/en.yml:

en:
  activerecord:
    attributes:
      person:
        first_name: 'Given name'

If no explicit translation is found, String#humanize is used.

This card explains where Rails will look for custom attribute name translations in your locale files.

Tip

Even if your application only supports a single language, it makes sense to store custom human attribute name in your locale files. This way you will not duplicate custom names throughout your code base. Also Rails will return the locale values in all methods that mention attribute names, like record.errors.full_messages Show archive.org snapshot .

With simple ActiveRecord models

If you have class Cat < ApplicationRecord, the call to Cat.human_attribute_name(:name) will look for translations in the following places:

  • activerecord.attributes.cat.name
  • activerecord.attributes.name (avoid)

With subclasses

If you have class Cat < Animal, the call to Cat.human_attribute_name(:name) will look for translations in the following places:

  • activerecord.attributes.cat.name
  • activerecord.attributes.animal.name
  • activerecord.attributes.name (avoid)

With namespaced models

Namespace separators (::) appear as a slash (/) in the scope names.

E.g. if you have a class Cat::Form < Cat, the call to Cat::Form.human_attribute_name(:name) will look in the following places:

  • activerecord.attributes.cat/form.name
  • activerecord.attributes.cat.name
  • activerecord.attributes.animal.name
  • activerecord.attributes.name (avoid)

With ActiveType form models

If you're using form models with ActiveType Show archive.org snapshot , a class Cat < ActiveType::Record[Animal] will look for its :name translation in the following places:

  • activerecord.attributes.cat.name
  • activerecord.attributes.animal.name
  • activerecord.attributes.name (avoid)

This is because Cat still inherits from Animal in this case, with some ActiveType magic sprinkled in between.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2024-07-10 11:06)