2010-12-18 116 views
4

使用:Rails的3.0.3,1.9.2紅寶石Rails 3中的I18n標籤翻譯中的has_many關係nested_attributes

這裏的關係:

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標籤,它不承認它。

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

我也曾嘗試:

person[contact_method_attributes] 

這只是正常爲1-1的關係,例如

person[wife_attributes]: 
    name: 'My wife' 

但不person[wives_attributes]

在此先感謝

回答

4

我這樣做有:

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

當你有無限的選擇,這是很好,但不理想。我只想說明在表單生成器中的自定義翻譯密鑰:)

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 %> 

編輯: 不知道,如果它是一個新的功能,但似乎像一個魅力做這個工作:

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

在Rails 3.2.12中,我無法獲得:'helpers.label.person.contact_method.info'的工作,但:'helpers.label.person [contact_method_attributes] .info'。 (這是爲has_one;我沒有嘗試過has_many關係。) – graywh 2013-03-13 20:40:58

+0

在Rails 3.1.10中,我可以得到:'helpers.label.person.contact_methods.info'來工作,但必須使用:'helpers.label .person [contact_methods_attributes] [new_contact_methods]'爲我的javascript-addable has_many關聯。 (當爲我的按鈕的data-content屬性呈現模板時,「new_contact_methods」是id的佔位符,該模板將字段添加到DOM。) – graywh 2013-03-13 21:12:55

0

在我的Rails應用程序3.2.13屬性標籤從模型自動拾取其屬性被嵌入。請注意,我嵌套了belongs_to模型的屬性,但它也可能以其他方式工作。

從工作中我的例子:

的車型:

class User < ActiveRecord::Base 
    belongs_to :account 
    accepts_nested_attributes_for :account 
    # ... 
end 

class Account < ActiveRecord::Base 
    has_many :users 
end 

的觀點:

<h2><%= t(:sign_up) %></h2> 

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> 
    <%= devise_error_messages! %> 

    <div><%= f.label :email %><br /> 
    <%= f.email_field :email %></div> 

    <%= f.fields_for :account do |account_form| %> 

    <div><%= account_form.label :subdomain %><br /> 
    <%= account_form.text_field :subdomain %>.<%= request.host %> <span class="hint"></span></div> 

    <% end %> 

translations_de.yml:

activerecord: 

models: 
    account: Konto 
    user: Benutzer 

attributes: 
    account: 
    name: Firmenname 
    subdomain: Subdomain 
    users: Benutzer 

    user: 
    # ... no sign of subdomain here ... 

和視圖渲染與蘇bdomain標籤翻譯基於

activerecord.attributes.account.subdomain 

不錯。 :)

我不確定,但它可能會要求您使用activerecord路徑而不是幫助者之一。

+0

請注意,如果對象還不存在('account_form.object'爲'nil'),Rails將不會在模型中查找翻譯。 – 2013-11-28 09:58:29