Rails - 通过活动资源使用 API 时 URL 中具有多个值的参数 [英] Rails - Parameter with multiple values in the URL when consuming an API via Active Resource

查看:32
本文介绍了Rails - 通过活动资源使用 API 时 URL 中具有多个值的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 API,它希望我按以下格式执行请求:

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

?filter=value1&filter=value2

但是,我使用的是 Active Resource,当我指定 :params 哈希时,我无法使相同的参数在 URL 中出现两次,我认为这是正确的.所以我不能这样做:

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" },因为哈希的第二个过滤索引将被忽略.

: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"] }

这将产生一个 URL,如:

Which will produce a URL like:

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

这对我来说似乎没问题,但 API 不接受它.所以我的问题是:

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?

推荐答案

要创建有效的查询字符串,可以使用

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

这篇关于Rails - 通过活动资源使用 API 时 URL 中具有多个值的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆