Search code examples
ruby-on-railsrails-i18n

Locale switcher. How to redirect back with changed locale?


Rails 4.2 application.

In the footer of the page I have such code:

  footer.footer
    .container
        = form_tag set_locale_path, method: :post, id: 'set_locale' do
          = select_tag "locale", options_for_select(I18n.available_locales, I18n.locale.to_s), onchange: ("$('#set_locale').submit();")

And Locales controller with set_locale action.

class LocalesController < ApplicationController
  skip_before_filter :authenticate_user!

  def set_locale
    I18n.locale = params[:locale]
    # redirect_to request.referrer
  end
end

I have access to previous url via request.referrer. That looks like: http://localhost:3000/en/users.

Is there any way to change locale without gsubing referrer string? Because if not - application will switch locale back to :en from referrer url.


Solution

  • I can't see an easy solution without gsubing the string. If the locale would be set with a get parameter instead of being part of the route it would be easier.

    Example

    http://localhost:3000/users?locale=en // Sets the locale to english
    

    In that case the url would stay the same but the locale would change.

    This is how i do it in my projects:

    before_action :set_locale
    
    def set_locale
      I18n.locale = locale || I18n.default_locale
    end
    
    def locale
      return params[:locale] if ["sv", "en"].include? params[:locale]
    end