How to use I18n from a controller in Rails

I have a PetsController in which a flash message is installed. Something like that:

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

This controller belongs to the administrator, so it is located at: app/controllers/admin/pets_controller.rb . I will use I18n, so I replaced the line in the t('controllers.admin.pet.treated') controller 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 that didn't work. I tried to find it on config/locales/controllers/admin/pets/en.yml , config/locales/controllers/admin/en.yml config/locales/controllers/en.yml and none of them worked, no translation was found.

How can I use translation from this controller?

+5
source share
4 answers

In the controller you use it like this

 I18n.t 'controllers.admin.pet.treated' 
+8
source
 def treat_dog #do somthing flash[:success] = t('controllers.admin.pet.treated') end 
0
source

Put it in config/locales/en.yml and it should work (you may have to restart the server).

This guide should help clear my head of the I18n. I give a link to the corresponding section, but I read it in full: http://guides.rubyonrails.org/i18n.html#adding-translations

If you insist on using file attachments, you need to enable it. The documentation reads:

The default locale loading mechanism in Rails does not load locale files in nested dictionaries, such as here. Therefore, for this to work, we must explicitly specify Rails to look further:

 # config/application.rb config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')] 
0
source

In the callback, it should be:

 add_breadcrumb proc{ I18n.t('home_page') }, :root_path 
0
source

Source: https://habr.com/ru/post/1234695/


All Articles