Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get raw params rather than the "processed into hashes" versions

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

like image 338
Max Williams Avatar asked Dec 16 '22 12:12

Max Williams


1 Answers

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"]]
like image 111
mu is too short Avatar answered Mar 17 '23 23:03

mu is too short