在Rails中排除ESPN API故障

时间:2013-06-11 05:57:04

标签: ruby-on-rails api methods espn

在我的rails应用程序中,我有一种通过其API捕获ESPN标题的工作方法。但是,当我试图复制它以捕获所有NFL球员时,该方法失败了。

这是通过IRB工作的标题方法,当我在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发表的第一篇文章,以便对我的问题的方法/格式提供反馈。

1 个答案:

答案 0 :(得分:0)

我得到了它的工作,这是我修改的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 / athletes / 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。)