Rails I18n ActiveRecord model attributes after migration

64 Views Asked by At

I started creating an app, and planned out my basic scaffolding. Let's say I created this resource:

rails g scaffold CircusAnimal fieldOne:string fieldTwo:string

I'm using Rails I18n to translate the labels on my forms using:

en:
  activerecord:
    attributes:
      circus_animal:
        fieldOne: Breed
        fieldTwo: Trainer

So far so good, when I generate a form with all the fields for a model translations are being picked up correctly:

<%= form.fields_for :circus_animals do |f| %>
  <%= f.label :fieldOne %>
  <%= f.text_field :fieldOne %>
  <%= f.label :fieldTwo %>
  <%= f.text_field :fieldTwo %>
<% end %>

Then I decided I needed another field for this form, so I ran a migration:

rails g migration add_fieldThree_to_circusAnimal fieldThree:integer
rails db:migrate

I added the new field to permitted fields in the controller, and I added it in the view.

<%= form.fields_for :circus_animal do |f| %>
  <%= f.label :fieldOne %>
  <%= f.text_field :fieldOne %>
  <%= f.label :fieldTwo %>
  <%= f.text_field :fieldTwo %>
+ <%= f.label :fieldThree %>
+ <%= f.number_field :fieldThree %>
<% end %>

I also added a translation in en.yml:

en:
  activerecord:
    attributes:
      circus_animal:
        fieldOne: Breed
        fieldTwo: Trainer
+       fieldThree: Age

However the label for fieldThree is not getting translated. I have tried to clobber assets, I have tried running rails db:schema:cache:clear, and I have tried running this in the rails console:

CircusAnimal.connection.schema_cache.clear!
CircusAnimal.reset_column_information

If I run CircusAnimal.columns I correctly see the fieldThree column.

How can I get the newly added field to be translated just like the previous two fields that were initially scaffolded?

1

There are 1 best solutions below

0
JohnRDOrazio On

My bad, I see what happened. The resource in question (let's call it CircusAnimal) belongs to another resource (let's call it Circus), and therefore the form fields for CircusAnimal were included on the view page for the Circus resource, along with the Circus form fields. I added :fieldThree on the view for the Circus resource and not on the view for the CircusAnimal resource: thus my custom i18n-tasks scanner was associating :fieldThree with the Circus resource rather than the CircusAnimal resource. To fix I simply added :fieldThree to the view for CircusAnimal, the scanner picked it up and correctly associated it with CircusAnimal. Now when I translate it in en.yml under the correct resource, the translation is correctly showing in the view. Sorry, dumb mistake! I figured it out by trying to do the translation in the rails console with I18n.t('activerecords.attributes.circus_animal.fieldThree') and I got an error that the translation key was missing. That got me to notice that the key was under the wrong resource, because it had been picked up from the view for the Circus resource!