Перевод метки Rails 3 I18n для вложенных_атрибутов в отношении has_many

Использование: 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

Теперь, когда я пытаюсь настроить метки contact_method в I18n, он их не распознает.

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]

заранее спасибо


person Garrett Lancaster    schedule 18.12.2010    source источник


Ответы (2)


Я сделал это с:

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'
person Clément    schedule 01.02.2011
comment
В Rails 3.2.12 мне не удалось заставить работать :'helpers.label.person.contact_method.info', но :'helpers.label.person[contact_method_attributes].info' работает. (Это было для has_one; я не пробовал с отношением has_many.) - person graywh; 14.03.2013
comment
В Rails 3.1.10 я мог заставить работать :'helpers.label.person.contact_methods.info', но должен был использовать :'helpers.label.person[contact_methods_attributes][new_contact_methods]' для моей ассоциации has_many с добавлением javascript. (new_contact_methods является заполнителем для идентификатора, когда шаблон отображается для атрибута содержимого данных моей кнопки, который добавляет поля в DOM.) - person graywh; 14.03.2013

В моем приложении Rails 3.2.13 метки атрибутов автоматически берутся из модели, атрибуты которой встроены. Обратите внимание, что я вложил атрибуты модели own_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 ...

И представление отображается с меткой поддомена, переведенной на основе

activerecord.attributes.account.subdomain

Хороший. :)

Я не уверен, но может потребоваться, чтобы вы использовали путь активной записи вместо вспомогательного.

person Till Otto    schedule 05.06.2013
comment
Обратите внимание, что если объект еще не существует (account_form.object равен nil), Rails не будет искать перевод в модели. - person Michaël Witrant; 28.11.2013