How to parse a multi-valued field from a URL request in Rails

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

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

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

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

+7
ruby ruby-on-rails
source share
2 answers

You can use the default Ruby CGI module to parse the query string in the Rails controller as follows:

 params = CGI.parse(request.query_string) 

This will give you what you want, but note that you will not get any other Rails extensions for parsing strings, for example using HashWithIndifferentAccess , so you will need strings, not Symbol characters.

In addition, I do not believe that you can set such parameters with a single line and overwrite the contents of the default rails params parameters. Depending on how broadly you want this change, you may need to patch the monkey or hack some internal details. However, the operational thing, if you want a global change, is to put this in the before filter in application.rb and use a new instance of var, such as @raw_params

+13
source share

I like the CGI.parse solution (request.query_string) mentioned in another answer. You can do this to combine a custom parsing string in params:

 params.merge!(CGI.parse(request.query_string).symbolize_keys) 
+2
source share

All Articles