Rails的current_path帮助程序?

19

我正在开发一个基于Rails 3.2的应用程序,具有以下路由条件:

scope "(:locale)", locale: /de|en/ do
  resources :categories, only: [:index, :show]
  get "newest/index", as: :newest
end

我有一个控制器,其包含以下内容:

class LocaleController < ApplicationController
  def set
    session[:locale_override] = params[:locale]
    redirect_to params[:return_to]
  end
end

我正在模板中使用以下内容:

我正在使用这个东西,像这样:
 = link_to set_locale_path(locale: :de, return_to: current_path(locale: :de)) do
   = image_tag 'de.png', style: 'vertical-align: middle'
     = t('.languages.german')

我想知道为什么在Rails中没有像current_path这样的助手,能够推断出我们当前使用的路由,并重新包含新选项进行重定向。
我的问题是使用类似redirect_to :back的东西,会将用户推回到/en/........(或/de/...),这会导致糟糕的体验。
直到现在,我一直在将语言环境存储在会话中,但这对Google和其他索引服务不起作用。
我相信如果我投入足够的时间,我可以想出一个聪明的方法来检测哪个路由匹配,并交换语言环境部分,但我觉得这将是一个hack。
我愿意听取所有想法,但这个SO问题建议只使用sub();不幸的是,由于语言环境短代码如此短且经常出现,可能并不明智。
2个回答

33
如果你正在使用:locale范围,你可以将url_for用作current_path
# Given your page is /en/category/newest with :locale set to 'en' by scope

url_for(:locale => :en) # => /en/category/newest
url_for(:locale => :de) # => /de/kategorie/neueste

4
不错的技巧,结果我写了这个函数:def current_path(options = {}); options = request.params.symbolize_keys.merge(options); url_for Rails.application.routes.recognize_path(request.path).merge(options) end,感觉有些复杂了! - Lee Hambley
1
你也可以不带任何参数使用 url_for - aef

6
如果有人在这里查看,您可以使用request.fullpath,它应该给出域名后的所有内容,因此将包括语言环境。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接