Search code examples
ruby-on-railsruby-on-rails-4localerails-i18n

Rails locale not persistent


I am trying to develop a dual language app.

However, I found that the locale change is not persistent by the default i18n gem.

I have this index page and provided a link to change the default language.

<% if I18n.locale == I18n.default_locale %>
 <%= link_to "English", :locale=>'en'%>
<% else %>
 <%= link_to "Français", :locale=>'fr'%>
<%end%>

The problem is that when I login to another page, the locale falls back to the default language.

So, I just wonder how to keep the user language choice and using that locale persistently until the user logs out.

Thanks in advance.


Solution

  • I recommend you to read this Rails guides about I18n to understand how I18n works in Rails. It's obvious that change of I18n.locale is temporary, and will be reset per session.

    According to your requirement, you can store the selected locale in session. Here is the sample code:

    # app/controllers/application_controller.rb
    class ApplicationController < ActionController::Base
      before_action :set_locale
    
      def set_locale
        I18n.locale = params[:locale] || session[:locale] || I18n.default_locale
        session[:locale] = I18n.locale
      end
    end
    

    Then you can clear the session[:locale] when user signed out.

    # app/controllers/sessions_controller.rb
    class SessionsController < ApplicationController
      def sign_out
        # ...
        session.delete :locale
      end
    end