Rails:更改语言环境并保留页面参数

问题描述:

我有一个导航栏,其中包含指向不同语言的链接:

I have a navbar with links to different languages:

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

问题是,当用户尝试在包含url中其他参数的页面上切换语言时.此时更改语言环境将重新加载页面并剥离所有其他参数.

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?

例如,当

/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.

这不是执行此操作的好方法.请参见下面的评论.

问题是创建语言环境切换器链接时您没有将当前参数传递给link_to.

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") %>

另请参阅:将查询字符串参数添加到link_to