Translated attributes in Rails error messages (Rails 2.3.2, I18N)

一曲冷凌霜 提交于 2019-12-20 14:12:33

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/898754/translated-attributes-in-rails-error-messages-rails-2-3-2-i18n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!