Rails 3 I18n label translation for nested_attributes in has_many relationship

后端 未结 2 1133
灰色年华
灰色年华 2021-01-13 18:37

Using: Rails 3.0.3, Ruby 1.9.2

Here\'s the relationship:

class Person < ActiveRecord::Base
  has_many :contact_methods
  accepts_nested_attributes         


        
2条回答
  •  灰色年华
    2021-01-13 19:26

    In my Rails 3.2.13 app the attribute labels are picked up automatically from the model whose attributes are embedded. Please note that I am nesting attributes of the belongs_to model, but it might also work the other way around.

    My example from working code:

    The models:

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

    The view:

    <%= t(:sign_up) %>

    <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= devise_error_messages! %>
    <%= f.label :email %>
    <%= f.email_field :email %>
    <%= f.fields_for :account do |account_form| %>
    <%= account_form.label :subdomain %>
    <%= account_form.text_field :subdomain %>.<%= request.host %>
    <% end %>

    translations_de.yml:

    activerecord:
    
     models:
      account: Konto
      user: Benutzer
    
     attributes:
      account:
        name: Firmenname
        subdomain: Subdomain
        users: Benutzer
    
      user:
        # ... no sign of subdomain here ...
    

    And the view is rendered with the subdomain label translated based on

    activerecord.attributes.account.subdomain
    

    Nice. :)

    I'm not sure but it might require you to use the activerecord path instead of the helpers one.

提交回复
热议问题