I'm trying to build a web api in ruby on rails, I'm using rest-client gem. I have tried this code in order to get a response from multiple urls and display the responses together
def index
url = (['http://example1','https://example2'])
url.split(",")
i = 0
url.each do |i|
render json: JSON.parse(RestClient::Request.execute( method: :get, url: url[i])), layout: nil
end
end
end
but i get an error message "no implicit conversion of String into Integer"
The error is coming from this line, rather than url[i]
, use just i
, as i is the url you are trying to access, as an example, to deal with the implicit conversion:
render json: JSON.parse(RestClient::Request.execute( method: :get, url: i)), layout: nil
But the core issue is rendering multiple times, this can be solved by getting the data you need first, and then render the array once at the end.
Like so:
def index
url_list = ['http://example1','https://example2']
responses = []
url_list.each do |url|
responses << JSON.parse(RestClient::Request.execute( method: :get, url: url))
end
render json: responses, layout: nil
end