views:

1726

answers:

2

I have a URL of form http://www.example.com?foo=one&foo=two

I want to get an array of values ['one', 'two'] for foo, but params[:foo] only returns the first value.

I know that if I used foo[] instead of foo in the URL, then params[:foo] would give me the desired array.

However, I want to avoid changing the structure of the URL if possible, since its form is provided as a spec to a client application. is there a good way to get all the values without changing the parameter name?

+6  A: 

You can use the default Ruby CGI module to parse the query string in a Rails controller like so:

params = CGI.parse(request.query_string)

This will give you what you want, but note that you won't get any of Rails other extensions to query string parsing, such as using HashWithIndifferentAccess, so you will have to us String rather than Symbol keys.

Also, I don't believe you can set params like that with a single line and overwrite the default rails params contents. Depending on how widespread you want this change, you may need to monkey patch or hack the internals a little bit. However the expeditious thing if you wanted a global change would be to put this in a before filter in application.rb and use a new instance var like @raw_params

dasil003
works like a charm, thanks. I just needed it in a single place in one controller, so I didn't even need to muck with params.
ykaganovich
+1  A: 

I like the CGI.parse(request.query_string) solution mentioned in another answer. You could do this to merge the custom parsed query string into params:

params.merge!(CGI.parse(request.query_string).symbolize_keys)
md
Automatically symbolizing will open yourself up for a DoS attack on your application. Ruby never garbage collects Symbol instances, thus they stay around in memory, doing nothing, until the app is rebooted.
François Beausoleil