Rails: changing the language and saving page settings

I have a navigation bar with links to different languages:

<%= link_to t('header.english'), locale: "en" %> 

The problem is that the user is trying to switch the language on the page that contains additional parameters in the URL. Changing the language at this point reloads the page and breaks all the additional parameters.

So, how to transfer all parameters from the current page to the local switch link?

For example, when

 /page/new?param1=1&param2=2 

open, and the user switches the locale,

 /page/new?locale=en 

opens and both optional parameters are removed from the URL.

+4
source share
2 answers

EDIT: THIS IS NOT A GOOD WAY TO DO IT. See comments below.

The problem is that you are not passing the current link_to parameters when creating links to the language switch.

Change your navigation link to:

 <%= link_to t('header.english'), params.merge(locale: "en") %> 

See also: Add request parameters to link_to

+5
source

If you need a local parameter to stay in all queries, it is useful to use this approach:

 # app/controllers/application_controller.rb def default_url_options(options={}) { locale: I18n.locale } end 

from rails

+8
source

Source: https://habr.com/ru/post/1437799/