ruby-on-rails

How to set default locale for a controller


Is it possible to set a default locale of controller in Rails. Suppose the application supports different language like, fr, nl, en, cn etc and I want to use 'en' as a default language for the Admin Dashboard Controller. Please suggest


Solution

  • Just use a before_action callback to set the default locale.

    class Admin::DashboardController
      before_action :set_default_locale
    
      # ...
    
      private
        def set_default_locale
          I18n.default_locale = :en
        end
    end
    

    However one thing to beware of is that I18n.default_locale is not thread safe and that setting it in one controller may have side effects in other controllers.