Phoenix: Query string array handling

Created on 8 Apr 2016  路  3Comments  路  Source: phoenixframework/phoenix

Environment

  • Elixir version (elixir -v): 1.2
  • Phoenix version (mix deps): 1.1.4
  • Operating system: OS X 10.11.4

    Expected behavior

Given a GET request to an endpoint with a query string containing an array, for example: /foo?bar=bat&bar=baz&bar=qux, I would expect to be able to retrieve that array in the controller.

An example using Node's querystring:

> querystring.parse('foo=bar&foo=baz&foo=qux');
{ foo: [ 'bar', 'baz', 'qux' ] }

Actual behavior

Only the last item in the array is available via the controller params, for example (given a query string like the above):

def index(conn, %{"foo" => foo}) do
  # foo => "qux"
end

Other Notes

Similar issue: #702

The above issue suggests that the answer to this one might be similarly, "do it in a plug," which is fine, just wanted to make sure I wasn't missing something about handling query strings. They're a little different in that this style of query string arrays is a little safer in terms of parsing, and honestly, the style I've actually seen used in the wild, so I thought I'd at least throw this out there.

Most helpful comment

If you want an array in your query string you should use the following syntax: foo[]=bar&foo[]=baz&foo[]=qux.

All 3 comments

If you want an array in your query string you should use the following syntax: foo[]=bar&foo[]=baz&foo[]=qux.

Hrm ok, that did the trick. For anyone that comes across this in the future, you can get around this by adding the brackets to any key that contains an array before serialization.

var qs = {
  "foo[]": ["bar", "baz", "qux"]
};
querystring.stringify(qs);
// 'foo%5B%5D=bar&foo%5B%5D=baz&foo%5B%5D=qux'

Can the expected behaviour described above be supported in Phoenix as well? I mean, in a future release. Just realised this is an old issue, but still valid.

Clojure and Python Django (see get_list) also use that scheme for example.

Was this page helpful?
0 / 5 - 0 ratings