views:

1671

answers:

3

I have defined translated attributes and model names in the translation file and Modelname.human_attribute_name(...) returns the correctly translated attribute name, but the attribute names in the error messages are untranslated. What is needed that the attribute names in the error messages are translated?

+3  A: 

From the Guide on the subject, you will need to set up the localization file properly with your model names and attribute names:

en: 
  activerecord: 
    models: 
      user: Dude 
    attributes: 
      user: 
        login: "Handle"

Since this is YAML, make sure all your "tabs" are actually two soft spaces. Then you can get them out with User.human_name and User.human_attribute_name(:login).

I didn't take that for gospel -- there could have been a bug. I tested it, and it works fine. I made a model named Model with an attribute title. Here is a snippet of my fr.yml file in config/locales:

fr:
  activerecord:
    models:
      model: "Sumfink"
    attributes:
      model:
        title: "Tiltile"

Here's the relevant view code:

<h1>New <%= Model.human_name %></h1>
<% form_for(@model) do |f| %>
  <%= f.error_messages %>
  <%= Model.human_attribute_name("title") %><br />
  <%= f.text_field :title %>
  <%= f.error_message_on :title %>
...

And a screenshot of the properly translated output: http://screencast.com/t/et5FhVe1Gp

Ian Terrell
Thank you very much for your detailed answer. I tried it with a new project. I used a translation file from an existing project and added a new model to test the translation and the translation worked immediately. I don't have access to the original translation file, where the strings were not used for translation, because it's at my workplace. I'll look at it on Monday to see what is different. The application with the successful translation was running on Linux, the application at work runs in Windows.
RainerB
My translation file was correct. I ommitted the "_id" part of the column name because they where not shown in the error message of the view. I used "model" instead of "model_id".
RainerB
A: 

Just wanted to say thanks to Ian, I had the same question and your answer was perfect. Just one question though, does either of you know why Model.human_attribute_name(:title) doesn't work? I thought symbol works wherever string does but it barfed on me.

Bob
+1  A: 

Kudos to Ian, just wanted to add that in order to highlight the label in case of a failed validation you need to write it like this:

  <%= f.label "title", Model.human_attribute_name("title") %><br />

For some reason, writing it just like:

  <%= f.label "title" %><br />

doesn't display the translation.

schastar
What version of Rails are you using? This bug of label was fixed in 2.3.6: https://rails.lighthouseapp.com/projects/8994/tickets/745-form-label-should-use-i18n
giraff