Ruby on Rails,如何使用i18n查看嵌套的多态?

时间:2015-06-23 05:53:14

标签: ruby-on-rails-4 polymorphic-associations rails-i18n

这些是我的模特

class Employee < ActiveRecord::Base
  has_many addresses, as: :locatable
end

class Client < ActiveRecord::Base
  has_many addresses, as: :locatable
end

class Address < ActiveRecord::Base
  belongs_to :locatable, polymorphic: true
end

我将路线设为

resources :employees do
    resources :addresses, :defaults => { :locatable => 'employee'}
end

resources :clients do
    resources :addresses, :defaults => { :locatable => 'clients'}
end

在地址_form.html.erb中,我正在尝试显示员工地址和客户地址的不同文本(例如,员工地址显示&#34;这些是已知的员工地址&#34;和客户地址显示&#34;客户可以在这里找到&#34;)。

这是我的i18n文件

en:
  employees:
    new:
      address: 'These are the known employee address'
    edit:
      address: 'These are the known employee address'
    show:
      address: 'These are the known employee address'
  clients:
    new:
      address: 'Clients can be found here'
    edit:
      address: 'Clients can be found here'
    show:
      address: 'Clients can be found here'

我能想到的两种方法。 第一个是使用延迟加载

t(.address)

将会有大量重复标签,因为&#34; new&#34;和&#34;编辑&#34;并且&#34;显示&#34;都有相同的标签。 第二种方法是使用范围,如

t .address, scope: [:locatable, :new, :address] 

这样,我不需要将地址分成新的,编辑和显示。但是,我不确定如何检索:可定位的范围。或者有更好的方法吗?

请帮忙!

1 个答案:

答案 0 :(得分:1)

经过数小时的试验和错误,由

解决
en:
  :employees:
    :address: 'These are the known employee address'
  :clients:
    :address: 'Clients can be found here'

在_form

<%= t("#{params[: locatable]}.address") %>

...简单