7

I have a navbar with links to different languages:

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

The problem is when user tries to switch language on a page which contains additional parameters in the url. Changing locale at this point reloads the page and strips all the additional parameters.

So, how do I pass all the parameters from the current page to the locale switch link?

For example, when

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

is open, and user switches the locale,

/page/new?locale=en

is opened, and both additional parameters are stripped away from the url.

Alexander Savin
  • 6,202
  • 3
  • 29
  • 41

2 Answers2

10

If you need locale param to stay in all requests it's good to use this approach:

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

from rails guide

Sergii Mostovyi
  • 1,361
  • 1
  • 15
  • 19
5

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

The problem is that you are not passing the current params to link_to when you create the locale switcher link.

Change your navbar link to:

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

See also: Add querystring parameters to link_to

Community
  • 1
  • 1
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • 1
    This will expose a lot of parameters that you may not want to expose, on certain pages, as `params` also includes POST data. – Franz Feb 15 '16 at 12:40
  • Sorry the comments above are correct, this is not a good way to do this. The params should be explicitly added. – Chris Salzberg Mar 11 '16 at 07:09