Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Parameter with multiple values in the URL when consuming an API via Active Resource

I am consuming an API that expects me to do requests in the following format:

?filter=value1&filter=value2

However, I am using Active Resource and when I specify the :params hash, I can't make the same parameter to appear twice in the URL, which I believe is correct. So I can't do this:

:params => {:consumer_id => self.id, :filter => "value1", :filter => "value2" }, because the second filter index of the hash will be ignored.

I know I can pass an array (which I believe is the correct way of doing it) like this:

:params => {:consumer_id => self.id, :filter => ["value1","value2"] }

Which will produce a URL like:

?filter[]=value1&filter[]=value2

Which to me seems ok, but the API is not accepting it. So my question are:

What is the correct way of passing parameters with multiple values? Is it language specific? Who decides this?

like image 375
Nobita Avatar asked Mar 15 '12 02:03

Nobita


People also ask

What is URL parameters in API?

API Query parameters can be defined as the optional key-value pairs that appear after the question mark in the URL. Basically, they are extensions of the URL that are utilized to help determine specific content or action based on the data being delivered. Query parameters are appended to the end of the URL, using a '?

What are parameters in Rails?

params comes from ActionController::Base, which is accessed by your application via ApplicationController. Specifically, params refers to the parameters being passed to the controller via a GET or POST request. In a GET request, params get passed to the controller from the URL in the user's browser.


2 Answers

http://guides.rubyonrails.org/action_controller_overview.html#hash-and-array-parameters

Try :filter[] => value, :filter[] => value2

like image 160
fatfrog Avatar answered Sep 19 '22 12:09

fatfrog


to create a valid query string, you can use

params = {a: 1, b: [1,2]}.to_query

http://apidock.com/rails/Hash/to_query
http://apidock.com/rails/Hash/to_param

like image 24
spr86 Avatar answered Sep 18 '22 12:09

spr86