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?
My bad, I see what happened. The resource in question (let's call it
CircusAnimal) belongs to another resource (let's call itCircus), and therefore the form fields forCircusAnimalwere included on the view page for theCircusresource, along with theCircusform fields. I added:fieldThreeon the view for theCircusresource and not on the view for theCircusAnimalresource: thus my customi18n-tasksscanner was associating:fieldThreewith theCircusresource rather than theCircusAnimalresource. To fix I simply added:fieldThreeto the view forCircusAnimal, the scanner picked it up and correctly associated it withCircusAnimal. Now when I translate it inen.ymlunder 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 withI18n.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 theCircusresource!