Ruby-on-rails 如何使用redirect_to 到带有查询参数的非Rails URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1730827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:57:30  来源:igfitidea点击:

How to use redirect_to to a non-Rails URL with query params?

ruby-on-railsredirect

提问by Masonoise

We just had an existing use of redirect_to break due to a Rails upgrade, and it led to a question. I've been experimenting, and I don't seem to find a way to use redirect_to to send the user to a non-Rails page with query parameters appended, except by manually constructing the URL string, which seems like a shame. Previously, just a simple:

由于 Rails 升级,我们刚刚使用了 redirect_to 中断,这导致了一个问题。我一直在试验,我似乎没有找到使用 redirect_to 将用户发送到附加了查询参数的非 Rails 页面的方法,除非手动构建 URL 字符串,这似乎很遗憾。以前,只是一个简单的:

redirect_to "http://www.web.com/myurl" "parm"

was working -- it appended "parm" onto the URL, and multiple parms were handled correctly. That's no longer the case, so I was wondering if there's a new/better way to do this. The docs imply that including a Hash should work, but it doesn't:

正在工作 - 它将“parm”附加到 URL 上,并且正确处理了多个参数。情况不再如此,所以我想知道是否有新的/更好的方法来做到这一点。文档暗示包含 Hash 应该有效,但它没有:

redirect_to ("http://www.web.com/myurl", :parm => "foo")
redirect_to ("http://www.web.com/myurl", { :parm => "foo" } )

Neither one works. Manually building the URL string works fine, but does anyone have an incantation that makes this work a nicer way?

一个都不行。手动构建 URL 字符串工作正常,但有没有人有一个咒语可以让这个工作变得更好?

回答by fgblomqvist

Running Rails 5.0 and found this to be the simplest solution:

运行 Rails 5.0,发现这是最简单的解决方案:

args = { foo: 'bar' }
redirect_to 'https://otherwebsite.com/path?' + args.to_query

The only other solution that I found on this page that worked was when specifying the host (see Topher Fangio's comment on his own post), however, then you also have to specify the port in case the original url is on a different port (which is usually the case for dev environments).

我在此页面上找到的唯一其他有效解决方案是指定主机时(请参阅 Topher Fangio 对他自己的帖子的评论),但是,如果原始 url 位于不同的端口上,您还必须指定端口(即开发环境通常是这种情况)。

回答by Topher Fangio

According to the documentation, any parameters that are not recognized by url_forare passed on to the Route modules, so in theory, your code should work unless your parameter overrides one of the default ones that it looks for.

根据文档,任何无法识别的参数都会url_for传递给 Route 模块,因此理论上,除非您的参数覆盖了它查找的默认参数之一,否则您的代码应该可以工作。

However, there is an :overwrite_paramshash that you can supposedly pass:

但是,:overwrite_params您应该可以传递一个散列:

redirect_to 'http://www.web.com/myurl', :overwrite_params => { :parm => 'foo' }

Hope this helps.

希望这可以帮助。