Ruby-on-rails 将参数值作为 rails 中的查询字符串传递给 redirect_to

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/715179/
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:06:17  来源:igfitidea点击:

Passing param values to redirect_to as querystring in rails

ruby-on-railsrubyredirectquery-string

提问by Justin

This should be simple, but I can't seem to find an easy answer.

这应该很简单,但我似乎找不到简单的答案。

How can I pass param values from the current request into a redirect_to call? I have some form values I'd like to pass into the query string of a GET redirect

如何将当前请求中的参数值传递到 redirect_to 调用中?我有一些表单值我想传递到 GET 重定向的查询字符串中

I'd like to do something like:

我想做类似的事情:

redirect_to @thing, :foo => params[:foo]

and get sent to:

并发送至:

http://things/4?[foo][key1]=val1&[foo][key2]=val2

Thanks!

谢谢!

Also - how could this be handled for a redirect_to :back?

另外 - 如何处理 redirect_to :back ?

redirect_to :back, :foo => params[:foo]

回答by Jordan Brough

The 'Record' form of redirect_touses the second argument only for the response status. You'll have to use another form of redirect_to, like the 'String' form. e.g.:

“记录”形式redirect_to的第二个参数仅用于响应状态。您必须使用另一种形式的 redirect_to,例如“字符串”形式。例如:

redirect_to thing_path(@thing, :foo => params[:foo])

which will work for nested params[:foo]params like you mentioned. Or, as Drew commented below, you can use polymorphic_url(or _path):

这将适用于params[:foo]您提到的嵌套参数。或者,正如 Drew 在下面评论的那样,您可以使用polymorphic_url(或 _path):

redirect_to polymorphic_path(@thing, :foo => params[:foo])

回答by Drew Blas

To add to Jordan's answer:

添加乔丹的回答:

If you don't know what type of object @thingmight be, you can use the universal polymorphic_urlmethod. This is the method that is called internally when you pass in an object to redirect_toanyway.

如果您不知道@thing可能是什么类型的对象,则可以使用通用polymorphic_url方法。这是当您以redirect_to任何方式传递对象时在内部调用的方法。