Rails 3 question.
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 fine normally and usually useful for eg Post.create(params[:post])
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"
.
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.
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.
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
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
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.
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"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With