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

让人想犯罪 __ 提交于 2019-12-03 15:44:45

问题


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?


回答1:


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




回答2:


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

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




回答3:


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"


来源:https://stackoverflow.com/questions/9713382/rails-parameter-with-multiple-values-in-the-url-when-consuming-an-api-via-acti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!