获取原始参数而不是“处理成散列";版本 [英] Get raw params rather than the "processed into hashes" versions

查看:32
本文介绍了获取原始参数而不是“处理成散列";版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 3 问题.

Rails 3 question.

如果我发送这样的请求 PUT http://myapp/posts/123?post[title]=hello

If i send a request like this PUT http://myapp/posts/123?post[title]=hello

然后在我的控制器中我得到 params = {:id =>123, :post =>{:title =>你好"}}

then in my controller i get params = {:id => 123, :post => {:title => "hello"}}

这通常很好,通常对例如 Post.create(params[:post])

This is fine normally and usually useful for eg Post.create(params[:post])

但是,在这种情况下,我需要访问参数的原始"形式,以便我可以命令它们提取值,将它们全部作为简单字符串处理,即我希望将它们列出,以便参数名称是"post[title]" 参数值为 "hello".

However, on this occasion i need to get access to the 'raw' form of the params so i can order them pull out the values, dealing with them all as simple strings, ie i want them listed so the param name is "post[title]" and the param value is "hello".

有什么方法可以获得这些值吗?我认为可能有一种 request 方法,它的参数是原始的字符串形式,但我找不到.

Is there any way i get get these values? I thought there might be a method of request that has the params in their original stringy form but i can't find one.

我曾想尝试使用 to_param 将散列转换回字符串,但这似乎很脏,而且可能没有必要.

It had occurred to me to try to convert the hash back into a string with to_param but this seems a but dirty and possibly unecessary.

作为奖励,我希望它忽略 :id 参数,实际上只是在 ?在原始请求中.事实上,如果我能取回原始请求字符串,即 "http://myapp/posts/123?post[title]=hello" 那么就可以了:我可以在?并从那里拿走.我突然想到我可能可以从标题中获取它.与此同时,如果有人知道更好的方法,请告诉我:)

As a bonus, i'd like it to ignore the :id parameter, literally just taking the part after the ? in the original request. In fact, if i can just get back the original request string, ie "http://myapp/posts/123?post[title]=hello" then that would do: i could split on the ? and take it from there. It just occurred to me that i can probably get it out of a header. In the meantime though, if anyone knows a nicer way then tell me please :)

感谢任何建议 - 最大

Grateful for any advice - max

推荐答案

请不要手动解析.从 Rails 请求中获取 URI:

Don't do the parsing by hand, please. Grab the URI from the Rails request:

url = request.url
# Or, depending on the Rails version and stack
url = request.request_uri
# Or even
url = request.scheme + '://' + request.host_with_port + request.fullpath

request.url 的返回值似乎取决于您的服务器堆栈,request.request_uri 应该可以解决这个问题,但在 Rails 3.1 中似乎不存在.第三种自己构建"方法应该在任何地方产生一致的结果.叹气.

The return value from request.url seems to depend on your server stack, request.request_uri is supposed to fix that but doesn't seem to exist in Rails 3.1. The third "build it all yourself" approach should produce consistent results everywhere. Sigh.

然后,一旦你有了 URI,使用 URI.parseURI.decode_www_form 来解析它:

Then, once you have the URI, use URI.parse and URI.decode_www_form to parse it:

u = URI.parse(url)
q = URI.decode_www_form(u.query)
# if u.query was "a=b&c=d&a=x" then q is
# [["a", "b"], ["c", "d"], ["a", "x"]]

这篇关于获取原始参数而不是“处理成散列";版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆