简体   繁体   English

Rails 3.1 翻译 model 属性名称

[英]Rails 3.1 translate model attribute name

I'm trying to customize (translate) an active record attribute name in rails 3.1 ("first_name").我正在尝试自定义(翻译)rails 3.1 中的活动记录属性名称(“first_name”)。 Here's beginning of my locale file (config/locales/sv.yml):这是我的语言环境文件 (config/locales/sv.yml) 的开头:

"sv":
  activerecord:
    models:
      employee: "Anställd"
    attributes:
      employee:
        first_name: "Förnamn"

I'm sure this file is used by rails because changing translations further down in the file works.我确信这个文件被 rails 使用,因为在文件中进一步更改翻译是可行的。 Here's the form field erb code that should say "Förnamn" not "First name":这是应该说“Förnamn”而不是“名字”的表单字段 erb 代码:

  <div class="field">
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name %>
  </div>

Running Employee.human_attribute_name(:first_name) in rails console returns "First name".在 Rails 控制台中运行Employee.human_attribute_name(:first_name)会返回“名字”。 Thank you very much非常感谢

In Rails 3.1 you can do it this way as well:在 Rails 3.1 中,您也可以这样做:

<% form_for @post do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>

en:
  helpers:
    label:
      post:
        title: 'Customized title'

This approach is ORM agnostic and works fine for active model (with mongoid for instance).这种方法与 ORM 无关,适用于活动 model(例如 mongoid)。

I realized that I had the activerecord entry defined two times in my sv.yml translation file which ment my attributes were overridden at the top of the file.我意识到我在我的 sv.yml 翻译文件中定义了两次 activerecord 条目,这表明我的属性在文件顶部被覆盖。 It works now.现在可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM