Get raw parameters, not hashed processed versions

Rails 3 questions.

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

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

This is normal and usually useful, for example Post.create(params[:post])

However, in this case, I need to access the "initial" form of the parameters, so I can order them to pull out the values, meaning all of them as simple strings, i.e. I want them to be listed, so the parameter name is "post[title]" and the parameter value is "hello" .

Is there any way to get these values? I thought there might be a request method that has parameters in its original lowercase form, but I cannot find it.

It occurred to me to try to convert the hash back to a string using to_param, but this seems dirty and maybe unnecessary.

As a bonus, I would like it to ignore the parameter: id, literally just taking part after? in the original request. Actually, if I can just return the original query string, that is, "http://myapp/posts/123?post[title]=hello" , then this would be: could I split by? and take it from there. It just occurred to me that I would probably choose this from the title. In the meantime, if anyone knows a better way, then tell me, please :)

Grateful for any advice - max

+4
source share
2 answers

Do not disassemble by hand, please. Take 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 

The return value from request.url seems to depend on your server stack, request.request_uri should fix this, but it doesn't seem to exist in Rails 3.1. The third โ€œdo it yourselfโ€ approach should produce universal results. Sigh.

Then, as soon as you have a URI, use URI.parse and URI.decode_www_form to URI.decode_www_form 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"]] 
+7
source

Request#body and Request#uri should help you. You can get the "raw" request data, but not some intermediate form ... although it is not so difficult to simply divide by ampersands and then again by "=" if you want key-value pairs;)

+3
source

All Articles