18

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?

Nobita
  • 23,519
  • 11
  • 58
  • 87
  • I'm a little confused. How can "filter" have 2 different values? – fatfrog Mar 15 '12 at 03:52
  • Sorry what I mean is, it looks like the way the API is written, the filter value will just be overwritten by the last value passed. – fatfrog Mar 15 '12 at 04:14
  • @fatfrog I don't know how the API is written, I am just fetching data according to their specs. But just so you know, the API is able to get the two values when their are passed like ?filter=value1&filter=value2 – Nobita Mar 15 '12 at 04:29
  • Ok updated my answer- according to the docs, To send an array of values, append an empty pair of square brackets “[]” to the key name. – fatfrog Mar 15 '12 at 04:34
  • @fatfrog You haven't written any answer. Also, read my question(s). Which docs do you refer to? – Nobita Mar 15 '12 at 05:20
  • Whoops sorry, posting from my phone and it didn't stick – fatfrog Mar 15 '12 at 08:13

3 Answers3

8

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

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

fatfrog
  • 2,118
  • 1
  • 23
  • 46
6

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

spr86
  • 76
  • 1
  • 4
1

You can generate query strings containing repeated parameters by making a hash that allows duplicate keys. Because this relies on using object IDs as the hash key, you need to use strings instead of symbols, at least for the repeated keys.

(reference: Ruby Hash with duplicate keys?)

params = { consumer_id: 1 } # replace with self.id
params.compare_by_identity
params["filter"] = "value1"
params["filter"] = "value2"
params.to_query #=> "consumer_id=1&filter=value1&filter=value2"
Tim Peters
  • 4,034
  • 2
  • 21
  • 27