Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse multivalued field from URL query in Rails

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?

like image 876
ykaganovich Avatar asked Apr 15 '09 18:04

ykaganovich


2 Answers

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

like image 177
gtd Avatar answered Sep 20 '22 20:09

gtd


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)
like image 35
md. Avatar answered Sep 17 '22 20:09

md.