How to use I18n from controller in Rails

Iván Cortés Romero picture Iván Cortés Romero · Oct 28, 2015 · Viewed 11.9k times · Source

I have a PetsController in which a flash message is setted. Something like this:

class PetsController

  ...

  def treat_dog
    #do somthing
    flash[:success] = 'Your dog is being treated.'
  end

  ...

end

this controller belongs to Admin, so it is located at: app/controllers/admin/pets_controller.rb. I will use I18n, so I replaced the string in controller with t('controllers.admin.pet.treated'), then,I wrote this yml:

en:
  controllers:
    admin:
      pet:
        treated: "Your dog is being treated."

located at: config/locales/controllers/admin/pet/en.yml and it did not work. I have attempted locating it at config/locales/controllers/admin/pets/en.yml, config/locales/controllers/admin/en.yml config/locales/controllers/en.yml and none of these worked, the translation is not found.

How can I use a translation from this controller?

Answer

Mahesh picture Mahesh · Oct 28, 2015

In controller you use it like this

I18n.t 'controllers.admin.pet.treated'

Using t() directly enables lazy loading:

t(".treated") #loads from key: controllers.admin.pet.treated