Ruby-on-rails 带参数的 Rails redirect_to
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9661611/
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
Rails redirect_to with params
提问by ygnhzeus
I want to pass parameters (a hash) to redirect_to, how to do this? For example:
我想将参数(散列)传递给redirect_to,该怎么做?例如:
hash = { :parm1 => "hi", :parm2 => "hi" }
and I want to redirect to page /hello
我想重定向到页面 /hello
URL like this: /hello?parm1=hi&parm2=hi
网址是这样的: /hello?parm1=hi&parm2=hi
回答by James
If you don't have a named route for /hello then you'll have to hardcode the params into the string that you pass to redirect_to.
如果您没有 /hello 的命名路由,那么您必须将参数硬编码到您传递给的字符串中redirect_to。
But if you had something like hello_paththen you could use redirect_to hello_path(:param1 => 1, :param2 => 2)
但是如果你有类似的东西,hello_path那么你可以使用redirect_to hello_path(:param1 => 1, :param2 => 2)
回答by jrochkind
Instead of:
代替:
redirect_to some_params
You can do:
你可以做:
redirect_to url_for(some_params)
You're turning the params into a url with url_forbefore passing it to redirect_to, so what you pass redirect_toends up being a URL as a string, which redirect_to is happy to redirect to.
在将参数url_for传递给 之前,您将参数转换为 url redirect_to,因此您传递的内容redirect_to最终是作为字符串的 URL,redirect_to 很乐意重定向到该 URL。
Note well: I don't understand why redirect_torefuses to use params. It used to be willing to use params. At some points someone added something to Rails to forbid it. It makes me suspect that there are security reasons for doing so, and if so, these security reasons could mean that manually doing redirect_to url_for(p)has security implications too. But I haven't yet been able to find any documentation explaining what's up here.
请注意:我不明白为什么redirect_to拒绝使用参数。它曾经愿意使用参数。在某些时候,有人在 Rails 中添加了一些东西来禁止它。这让我怀疑这样做有安全原因,如果是这样,这些安全原因可能意味着手动操作redirect_to url_for(p)也有安全隐患。但我还没有找到任何解释这里发生了什么的文档。
update: I've found the security warning, but haven't digested it yet: https://github.com/rails/rails/pull/16170
更新:我找到了安全警告,但还没有消化它:https: //github.com/rails/rails/pull/16170
回答by JacobEvelyn
The easiest way (if it's not a named route) will be:
最简单的方法(如果它不是命名路由)将是:
redirect_to "/hello?#{hash.to_param}"
redirect_to "/hello?#{hash.to_param}"
回答by Aghyad
Simply, pass the hash into an argument in the URL, and in your code parse it to get out all needed values.
简单地,将哈希传递给 URL 中的一个参数,然后在您的代码中解析它以获取所有需要的值。
param_arr = []
hash.each do |key , val|
param_arr << "#{key}=#{val}"
end
params_str = param_arr.join("&")
redirect_to "http://somesite.com/somepage?#{params_str}"
I know this might be very basic way to do it, but hey, it'll get you somewhere :)
我知道这可能是非常基本的方法,但是嘿,它会带你到某个地方:)

