Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 查询字符串的Rails路由重定向_Ruby On Rails - Fatal编程技术网

Ruby on rails 查询字符串的Rails路由重定向

Ruby on rails 查询字符串的Rails路由重定向,ruby-on-rails,Ruby On Rails,我有一个问题,最近一个控制器的名字改变了 我将路由文件更改为使用旧控制器名称接受呼叫,适用于书签引用旧名称的人: 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}') 那很好。但对于带有查询字符串的调用,它会将其阻止到/r

我有一个问题,最近一个控制器的名字改变了

我将路由文件更改为使用旧控制器名称接受呼叫,适用于书签引用旧名称的人:

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&end=2013-10-19&num_结果=294540&start=2013-10-13

它将url剪切为:

old/report/200


并显示由于缺少参数而导致的错误。你知道我能做什么吗?(我认为路线中的:sub_路径线会有帮助,但不会):(

马特提到的问题帮助我找到了答案(非常感谢!)。这与我的具体情况略有不同。我将对我有用的答案留作将来参考

match "/old/report/:client" => redirect{ |params, request| "/new/report/#{params[:client]}?#{request.query_string}" }

基于Alejandra的答案,更加详细,但如果没有查询字符串,则没有

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
修改
重定向
以使用
路径:
选项保留查询字符串:

-get'/old/about',to:redirect('/new/about'))
+获取“/old/about”到:重定向(路径:“/new/about”)

这在
重定向的API文档中得到了演示,请参见

现有的答案工作得很好,但不太适合保持干燥-一旦需要重定向多个路由,就会有大量重复的代码

在这种情况下,自定义重定向器是一种优雅的方法:

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]}"))

我写了一个更详细的解释。

可能重复:我想你可能是对的,让我检查一下,非常感谢!我会稍微修改一下,检查request.query\u字符串作为当前解决方案出现时是否总是会在底部添加“?”。