How to use I18n from controller in Rails How to use I18n from controller in Rails ruby-on-rails ruby-on-rails

How to use I18n from controller in Rails


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


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


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

This guide should help clear the head about I18n. I'm giving link to relevant section, but read it in full: http://guides.rubyonrails.org/i18n.html#adding-translations

If you insist on using nested files, you need to enable it. Documentation says:

The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further:

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