1

在我的 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 上的第一篇文章,因此对我的问题的方法/格式的反馈持开放态度。

4

1 回答 1

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。)

于 2013-06-11T17:50:25.367 回答