Changing the language by I18n on ruby on rails - leads to the fact that the language sometimes changes by itself

533 Views Asked by At

I made a language change and it works, but sometimes after several page updates, the language changes to another, then back - please help, I don't know what to do here

Method for lang change:

def switch_locale
  locale = params[:format].to_sym
  I18n.locale = locale

  redirect_to request.referrer
end

buttons for lang change:

    .min-h-screen.flex.flex-col.items-center.justify-start.fixed.top-0.left-0.w-full.pb-12.pt-32
      = button_to("rus", switch_locale_path('ru'), class: "btn font-bold btn-main rounded-lg fixed top-0", style: "right: 0.25rem")
      = button_to("en", switch_locale_path('en'), class: "btn  font-bold btn-main rounded-lg fixed top-0", style: "right: 4rem")
1

There are 1 best solutions below

0
Gilmore Garland On

I suggest you to put locale in cookies so it can be persisted in user's browser (more about it here). Adding || root_path is important, as user can access switch_locale directly in their browser's address bar, so user will not have error when they do that.

def switch_locale
  cookies[:locale] = params[:format].to_sym

  redirect_to request.referrer || root_path
end

then use before_action on ApplicationController to set locale from cookies, so user will have same experience when access any page after switch language, and if cookies does not exist we can use default locale (you can replace :en with I18n.default_locale if you want to use default from I18n config)

class ApplicationController < ActionController::Base
  before_action :set_locale
  
  private
  
  def set_locale
    I18n.locale = cookies[:locale] || :en
  end
end