我遇到了问题,最近控制器的名称发生了变化。
我将路由文件更改为接受使用旧控制器名称的呼叫,对于具有引用旧名称的书签的人:
get '/old/about', to: redirect('/new/about')
get '/old/report/:client', to: redirect('/new/report/%{client}')
get '/old/:sub_path', to: redirect('/new/%{sub_path}')
工作正常。但对于带有查询字符串的调用,它会将其阻止为/ report / 200。例如:
/旧/报告/ 200 C_ID = 257&安培;端= 2013年10月19日&安培; NUM_RESULTS = 294540&安培;起始= 2013年10月13日
它将网址剪切为:
旧/报告/ 200
由于缺少参数而显示错误。你知道我能做什么吗? (我认为路线中的:sub_path行有帮助但不是):(
答案 0 :(得分:12)
修改redirect
以使用path:
选项保留查询字符串:
- get '/old/about', to: redirect('/new/about')
+ get '/old/about', to: redirect(path: '/new/about')
这在redirect
的API文档中有所体现,请参阅http://api.rubyonrails.org/classes/ActionDispatch/Routing/Redirection.html#method-i-redirect
答案 1 :(得分:11)
Matt提到的问题帮助我弄清楚了答案(非常感谢!)。这与我的具体案例略有不同。我留下的答案对我有用,以备将来参考。
match "/old/report/:client" => redirect{ |params, request| "/new/report/#{params[:client]}?#{request.query_string}" }
答案 2 :(得分:1)
基于亚历杭德拉的答案,更详细,但如果没有查询字符串则没有?
:
get "/old/report/:client", to: redirect{ |params, request| ["/new/report/#{params[:client]}", request.query_string.presence].compact.join('?') }
因此/old/report/:client?with=param
将成为/new/report/:client?with=param
,
/old/report/:client
将成为/new/report/:client
。
答案 3 :(得分:0)
现有的答案可以很好地工作,但不太适合保持干燥状态–一旦您需要重定向多个路径,就会有很多重复的代码。
在这种情况下,自定义重定向器是一种很好的方法:
class QueryRedirector
def call(params, request)
uri = URI.parse(request.original_url)
if uri.query
"#{@destination}?#{uri.query}"
else
@destination
end
end
def initialize(destination)
@destination = destination
end
end
现在,您可以为redirect
方法提供此类的新实例:
get "/old/report/:client", to: redirect(QueryRedirector.new("/new/report/#{params[:client]}"))
我有一封an article的书,上面有更详细的说明。