在我的rails应用程序中,我有一个通过API捕获ESPN头条新闻的有效方法。但是,当我尝试复制这个来捕获所有NFL球员时,该方法失败了。
这是通过IRB工作的headline方法,当我在IRB中运行Headline.all时,它工作得很好。
MODEL (headline.rb)
class Headline
include HTTParty
base_uri 'http://api.espn.com/v1/sports'
def self.all
response = Headline.get('/news/headlines',
:query => { :apikey => 'my_api_key' })
response["headlines"]
end
end
CONTROLLER (headlines_controller.rb)
class HeadlinesController < ApplicationController
def index
@headlines = Headline.all
end
end这是几乎相同的NFL球员代码,它通过IRB返回"nil“。你知道为什么吗?
MODEL (athlete.rb)
class Athlete
include HTTParty
base_uri 'http://api.espn.com/v1/sports'
def self.all
response = Athlete.get('/football/nfl/athletes',
:query => { :apikey => 'my_api_key_from_espn' })
response["athletes"]
end
end
CONTROLLER (athletes_controller.rb)
class AthletesController < ApplicationController
def index
@athletes = Athlete.all
end
end更新:我应该说我可以通过浏览器成功运行GET请求(并通过...http://api.espn.com/v1/sports/football/nfl/athletes/?apikey=my_api_key_from_espn查看结果)。
谢谢。这是我在StackOverflow上的第一篇帖子,所以对我的问题的方法/格式的反馈是开放的。
发布于 2013-06-12 01:50:25
我让它正常工作了,下面是我为Athlete.all修改的方法语法。基本上,需要对运动员api响应数组进行比标题API更深一点的遍历。
class Athlete
include HTTParty
base_uri 'http://api.espn.com/v1/sports'
def self.all
response = Athlete.get('/football/nfl/athletes',
:query => { :apikey => 'my_api_key_from_espn' })
response['sports'].first['leagues'].first['athletes']
end
end为了更好地衡量,下面是我的app/views//index.html.erb语法:
<ul id="athletes">
<% @athletes.each do |item| %>
<li class="item"><%= link_to item["displayName"], item["links"]["web"]["athletes"]["href"] %></li>
<% end %>
</ul>(特别感谢@ivanoats,当然还有@deefour。)
https://stackoverflow.com/questions/17037386
复制相似问题