2

I’m positive this is a dupe, but I couldn’t find the original.

Given a GET-style string like foo=bar&x[0]=baz, how can I decode this into a params-like array in a Rails app?


Updated to add: Note that CGI.parse seems to do much less than whatever magic Rails does:

1.9.3p194 :006 > CGI::parse 'foo=bar&x[foo][bar]=baz'
 => {"foo"=>["bar"], "x[foo][bar]"=>["baz"]} 

CGI.parse didn’t unpack the nested objects into a mult-level hash. In Rails, at some level, this is actually examined.

Alan H.
  • 16,219
  • 17
  • 80
  • 113
  • Here's one with several possible answers: [How to extract URL parameters...](http://stackoverflow.com/questions/2500462/how-to-extract-url-parameters-from-a-url-with-ruby-or-rails) – Zach Kemp Oct 17 '12 at 18:06

1 Answers1

9

For nested queries, Rails uses Racks' parameter parser Rack::Utils.parse_nested_query:

Rack::Utils.parse_nested_query 'foo=bar&x[foo][bar]=baz'
 => {"foo"=>"bar", "x"=>{"foo"=>{"bar"=>"baz"}}}
cdesrosiers
  • 8,862
  • 2
  • 28
  • 33
  • Thanks. It seems Rails does more magic on top of this, though, especially w.r.t. hard brackets. Editing my question to add this. – Alan H. Oct 17 '12 at 17:53