Rails 上的 Ruby:尝试根据值数组发出多个 API 请求。如何将这些值作为参数插入 API URL?

Ruby on Rails: Trying to make multiple API requests based on an array of values. How can I insert these values as parameters into the API URL?

我在 Rails (v6.0.3.2) 上使用带有 Ruby 的 rest-client (2.1.0-x64-mingw32)。

我正在尝试根据一组值发出多个 API 请求。

例如,这是一个短数组,其中包含要作为参数插入到 API URL 中的值:

array = ["DUBLIN%20CITY%20COUNCIL", "SOUTH%20DUBLIN%20COUNTY%20COUNCIL"]

然后我将使用循环将这些插入到每个请求中,结果如下:

https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=DUBLIN%20CITY%20COUNCIL&CategorySelected=OFFICE&Format=json&Download=false

https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=SOUTH%20DUBLIN%20COUNTY%20COUNCIL&CategorySelected=OFFICE&Format=json&Download=false

首先,尝试插入单个值,我试过这个:

require 'rest-client'
require 'json'

localAuthority = "DUBLIN%20CITY%20COUNCIL"

response = RestClient.get('https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=#{localAuthority}&CategorySelected=OFFICE&Format=json&Download=false')
json = JSON.parse(response)

但是,这会导致以下错误:

rails aborted!
URI::InvalidURIError: bad URI(is not URI?): "https://api.valoff.ie/api/Property/GetProperties?Fields=*&LocalAuthority=\#{localAuthority}&CategorySelected=FUEL/DEPOT&Format=json&Download=false"

该值似乎没有正确传递到 URL。如何将这些值作为参数插入 API URL?

仔细看看错误。错误消息中的 URL 包含字符串

...#{localAuthority}...

插值不起作用,因为 ruby 仅支持 双引号 字符串中的 #{} 语法。

尝试将单引号替换为双引号 (")

"...#{localAuthority}..."

我会省去有关清理输入的讲座,但请注意这些字符串的来源,并确保正确转义它们。