4

In Rails, when you want to send a list of values through a single array parameter, you usually do so by suffixing the URL parameter key with []. For example, the query string ?foo[]=1&foo[]=2&foo[]=3 is parsed as

params = { "foo" => [ 1, 2, 3 ] }

But for ?foo=1&foo=2&foo=3, only the last argument shows up in the params hash:

params = { "foo" => 3 }

Everything's fine while you can control the URL format; you can just use the [] syntax. But what if the URL is constructed by a remote system that you cannot influence, and that insists on the second format? How can one get the arguments unpacked properly?

Community
  • 1
  • 1
Stefan Majewsky
  • 5,427
  • 2
  • 28
  • 51
  • You are going to need to parse the URI manually, you can use [URI::decode_www_form](http://ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html#method-c-decode_www_form) – max Jun 03 '15 at 10:00
  • go through the https://github.com/sporkmonger/addressable - replacement for Ruby's URI module. – Pardeep Dhingra Jun 03 '15 at 10:09

1 Answers1

1

Using the hint from @maxcal I came up with this solution (to avoid adding yet more gems to this completely bloated app that I'm working on):

current_query_string = URI(request.url).query
foo_values = URI::decode_www_form(current_query_string).
  select { |pair| pair[0] == "foo" }.
  collect { |pair| pair[1] }
Stefan Majewsky
  • 5,427
  • 2
  • 28
  • 51