Common Ruby on Rails i18n Active Record attributes

Did you know that you can simplify your rails active record i18n locale files with a common attributes section?

I added translations for created_at and updated_at to all my models and thought "there must be a better way to do this šŸ§".

Reading through the rails i18n code, it turns out there is a solution.

So instead of adding common attributes to each model, define a top level `attributes' section.

Before:

# config/locals/active_record.en.yml
---
en:
  activerecord:
    attributes:
      user:
      created_at: Created at
      updated_at: Updated at
      email: E-mail
    room:
      created_at: Created at
      updated_at: Updated at
      name: Name

After:

# config/locals/active_record.en.yml
---
en:
  attributes:
    created_at: Created at
    updated_at: Updated at
  activerecord:
    attributes:
      user:
        email: E-mail
      room:
        name: Name

With this I can easily keep translations for common attributes in sync.

I hope you found this article useful and that you learned something new.

If you have any questions or feedback, didn't understand something, or found a mistake, please send me an email or drop me a note on twitter / x. I look forward to hearing from you.

PleaseĀ subscribe to my blogĀ if you'd like to receive future articles directly in your email. If you're already a subscriber, thank you.