Ruby on Rails, how to use i18n look up on nested polymorphic?

299 views Asked by At

These are my models

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

And I set my routes to be

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

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

And in address _form.html.erb, I am trying to show different text for employee address and clients address (for example, employee address show "These are the known employee address", and clients address show "Clients can be found here").

This is my i18n file

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'

The 2 approaches I can think of. The first one is to use lazy load

t(.address)

which will have a load of repeated labels, since "new" and "edit" and "show" all have the same label. The 2nd approach is to use scoped, something like

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

This way, I won't need to separate address into new, edit, and show. However, I'm not sure how to retrieve :locatable scope. Or is there a better approach for this?

Please help!

1

There are 1 answers

0
hook38 On BEST ANSWER

After hours of trial and errors, solved by

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

And in the _form

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

simple...