Localise nested virtual attribute in Rails

2019-05-14 02:06发布

问题:

How is it possible to localise nested virtual attribute in Rails?

The model:

class User < ActiveRecord::Base
  attr_accessor :company_information # This is used in callbacks etc
end

and the view:

= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: {class: 'form-horizontal'}) do |f|
  = devise_error_messages!
  = f.input :email
  = f.input :password
  = f.input :password_confirmation
  = f.simple_fields_for :company_information do |c|
    = c.input :name # This is what I want to localise
  = f.button :submit

The translation keys (from en.yml) like activerecord.attributes.user.company_information.name and activerecord.attributes.user.company_information_name aren't picked up.

回答1:

It seems you are using simple_form gem for generation of forms. Here is what worked for me.

en:
  simple_form:
    labels:
      user:
        company_information:
          name: My Name

The link to simple form's localization chapter may be also useful.



回答2:

In rails 3 i found one way. In your case translation would be helpers.label.user[company_information].name in en.yml it would look like this

en:
  helpers:
    label:
      "user[company_information]":
        name:"Name"