Rails current_path 助手? [英] Rails current_path Helper?
问题描述
我正在处理具有以下路由条件的 Rails 3.2 应用程序:
I'm working on a Rails 3.2 application with the following routing conditions:
scope "(:locale)", locale: /de|en/ do
resources :categories, only: [:index, :show]
get "newest/index", as: :newest
end
我有一个具有以下功能的控制器:
I've a controller with the following:
class LocaleController < ApplicationController
def set
session[:locale_override] = params[:locale]
redirect_to params[:return_to]
end
end
我在模板中使用了类似的东西:
I'm using this with something like this in the templates:
= 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
之类的帮助程序,它可以推断出我们当前正在使用的路由,并重新路由到它包含新选项.
I'm wondering why there doesn't exist a helper in Rails such as current_path
, something which is able to infer what route we are currently using, and re-route to it include new options.
我遇到的问题是使用类似 redirect_to :back
的东西,将用户推回到 /en/........
(或 /de/...
) 这会带来糟糕的体验.
The problem I have is using something like redirect_to :back
, one pushes the user back to /en/........
(or /de/...
) which makes for a crappy experience.
到目前为止,我一直在会话中存储语言环境,但这不适用于 Google 和其他索引服务.
Until now I was storing the locale in the session, but this won't work for Google, and other indexing services.
我敢肯定,如果我投入足够的时间,我可以做出一些足够聪明的事情来检测匹配的路由,并换掉语言环境部分,但我觉得这将是一个黑客.
I'm sure if I invested enough time I could some up with something that was smart enough to detect which route matched, and swap out the locale part, but I feel like this would be a hack.
我对所有想法持开放态度,但是这个SO 问题 建议只使用 sub()
;不幸的是,对于像语言环境短代码这样短且频繁出现的字符串,可能不太明智.
I'm open to all thoughts, but this SO question suggests just using sub()
; unfortunately with such short and frequently occurring strings as locale short codes, probably isn't too wise.
推荐答案
如果您使用的是 :locale
范围,您可以使用 url_for
作为 current_path代码>:
If you are using the :locale
scope, you can use url_for
as 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
这篇关于Rails current_path 助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!