JeffO
JeffO

Reputation: 137

How to translate ActiveModel attribute values in Rails 6.0

I have a status table with 10 different statuses. The columns are id and name.

When I display the "name" attribute in the view (especially as a nested attribute), I can't seem to figure out how to translate the value.

For example:

<%= t'@tank.status.name' %>

I tried adding the following to my fr.yml file

new: "Nouveau"
activerecord:
    models:
      status:
        one: 'Statut'
        other: 'Statuts'
        attributes:
          name:
            new: 'Nouveau'

but it didn't seem to access either of these entries.

How can I translate nested attribute values?

Edit

This sloppy way works, but it seems...just wrong.

class Status < ApplicationRecord
def name
  case id
  when 1
    I18n.t('new')
  when 2
    ..
  end
end

Is there a cleaner way to do this? That code makes me want to take a shower.

Upvotes: 0

Views: 891

Answers (1)

eux
eux

Reputation: 3282

Indentation is important in YML file, you could try this:

activerecord:
    models:
      status:
        one: 'Statut'
        other: 'Statuts'
    attributes:
      status/name:
        new: 'Nouveau'

Then Status.human_attribute_name('name.new') will reutrn 'Nouveau'.

Check out details on Rails Guides - Translations for Active Record Models

Upvotes: 2

Related Questions