19

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?

6
  • I'm a little confused. How can "filter" have 2 different values? Commented Mar 15, 2012 at 3: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. Commented Mar 15, 2012 at 4: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 Commented Mar 15, 2012 at 4: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. Commented Mar 15, 2012 at 4:34
  • @fatfrog You haven't written any answer. Also, read my question(s). Which docs do you refer to? Commented Mar 15, 2012 at 5:20

3 Answers 3

8

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.