本文介绍了has_many关系中nested_attributes的Rails 3 I18n标签转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:Rails 3.0.3,Ruby 1.9.2

Using: Rails 3.0.3, Ruby 1.9.2

这里是关系:

class Person < ActiveRecord::Base
  has_many :contact_methods
  accepts_nested_attributes_for :contact_methods
end

class ContactMethod < ActiveRecord::Base
  attr_accessible :info
  belongs_to :person
end

现在,当我尝试自定义I18n中的contact_method标签时,它无法识别.

Now when I try to customize the contact_method labels in I18n, it doesn't recognize it.

en:
  helpers:
    label:
      person[contact_methods_attributes]: 
        info: 'Custom label here'

我也尝试过:

person[contact_method_attributes]

这对于1-1关系很有效,例如.

This works just fine for 1-1 relationships, e.g.

person[wife_attributes]: 
  name: 'My wife'

但不是person[wives_attributes]

预先感谢

推荐答案

我这样做是:

en:
  helpers:
    label:
      person[contact_methods_attributes][0]: 
        info: 'First custom label here'
      person[contact_methods_attributes][1]: 
        info: 'Second custom label here'

这是不错的选择,但是当您有无限的选择时并不理想.我只需要在表单生成器中指定自定义翻译键即可:)

Which is nice but not ideal when you have unlimited options.. I would just specify a custom translation key in the form builder :)

en:
  helpers:
    label:
      person[contact_methods_attributes][any]: 
        info: 'Custom label here'

<% fields_for :contact_methods do |builder| %>
  <%= builder.label :info, t("helpers.person[contact_methods_attributes][any].info") %>
  <%= builder.text_field :info %>
<% end %>

不知道这是否是一项新功能,但这样做似乎很吸引人:

EDIT : Don't know if it's a new feature but seems to work like a charm doing this :

en:
  helpers:
    label:
      person:
        contact_methods: 
          info: 'Custom label here'

这篇关于has_many关系中nested_attributes的Rails 3 I18n标签转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 00:14