Search code examples
ruby-on-railscachingherokurails-i18n

RubyOnRails - Does not keep the selected language when I refresh the page


In development mode all work fine. But not in production mode on heroku.

When I select a locale and I refresh the page, it displays language by default half the time and the language I selected otherwise. I do not know what to do. I tried to clear the cache with Rails.cache.clear command, but it does not work. I guess the problem is with the cache system. I'm new to ruby on rails. Someone would have an idea how to fix this?

to understand my problem, you can go to my website, select the French language and refresh the page several times. Once the page is in French. Another time in English.

https://releaseit.herokuapp.com/

my application_controller:

  before_action :set_locale
  def set_locale
    if params[:locale].in? %W(en fr)
      I18n.locale = params[:locale]
    end
  end

The config files are same as here: https://github.com/starterkits/rails4-starterkit/tree/master/config

Sorry for my english (I am french and i use google translator)


Solution

  • I don't know (or see) where do you pass locale in URL. As far as I know in order to use params[:locale] your URL should look like:

    https://releaseit.herokuapp.com/fr/something
    https://releaseit.herokuapp.com/en/something
    https://releaseit.herokuapp.com/en
    https://releaseit.herokuapp.com?locale=fr
    

    http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-url-params

    What is more try my set_locale method:

      def set_locale    
        if params[:locale]
          I18n.locale = params[:locale] || I18n.default_locale
        else
          I18n.locale = http_accept_language.compatible_language_from(
            I18n.available_locales
          )
        end
      end
    

    set_locale method should be executed on every page reload to set proper locale each time.

    It requires http_accept_language gem from: https://github.com/iain/http_accept_language

    Check out also route_translator gem for creating routes with locale.