简体   繁体   English

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

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

We just had an existing use of redirect_to break due to a Rails upgrade, and it led to a question. 由于Rails升级,我们刚刚使用了redirect_to break,这导致了一个问题。 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. 我一直在尝试,我似乎没有找到一种方法使用redirect_to将用户发送到附加查询参数的非Rails页面,除非通过手动构建URL字符串,这似乎是一种耻辱。 Previously, just a simple: 以前,只是一个简单的:

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

was working -- it appended "parm" onto the URL, and multiple parms were handled correctly. 工作 - 它将“parm”附加到URL,并正确处理多个parms。 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: 文档暗示包含哈希应该有效,但它不会:

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字符串工作正常,但有没有人有一个咒语,使这项工作更好的方式?

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在不同的端口上,你还必须指定端口(通常是开发环境的情况)。

According to the documentation , any parameters that are not recognized by url_for are 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_params hash that you can supposedly pass: 但是,有一个:overwrite_params哈希你可以传递:

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM