我想用api中的数据填充我的数据库表。我有参与,并建立了三个模型,如下图所示:使用外部API请求数据填充rails数据库
class Fixture < ActiveRecord::Base
belongs_to :homeTeam, class_name: "Team", foreign_key: "homeTeam_id"
belongs_to :awayTeam, class_name: "Team", foreign_key: "awayTeam_id"
belongs_to :league
validates :matchday, presence: true
validate :opposing_teams_must_be_different
#validates :externalFixtureID, :date, :matchday, :awayTeam, :homeTeam , :goalsHomeTeam, :goalsAwayTeam, presence: true
def teams
[homeTeam, awayTeam]
end
def opposing_teams_must_be_different
errors.add(:awayTeam, "must be different from Home team") if awayTeam_id == homeTeam_id
end
class Team < ActiveRecord::Base
belongs_to :league
has_many :fixtures
end
class League < ActiveRecord::Base
has_many :teams
has_many :fixtures
end
来填充数据库,并确保我获得了联赛和球队赛程,我用灯具模型下面的代码:
def self.query_fixtures
uri = URI.parse("http://api.football-data.org")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new("/alpha/soccerseasons/354/fixtures")
response = http.request(request)
parsed_matches = JSON.parse(response.body)["fixtures"]
parsed_matches.each do |key, val|
@league = League.find(5)
@teams = @league.teams.each do |t|
if key["homeTeamName"] = t.name
homeTeam_id = t.id
elsif key["awayTeamName"] = t.name
awayTeam_id = t.id
end
@fixture = @league.fixtures.create!(:gameDate => key["date"], :matchday => key["matchday"], :awayTeam_id => awayTeam_id,
:homeTeam_id => homeTeam_id, :goalsHomeTeam => key["result"]["goalsHomeTeam"],
:goalsAwayTeam => key["result"]["goalsAwayTeam"])
end
end
end
但是,当我在rails控制台中运行代码时,数据库会被填充,但awayTeam_id仍然为空/空。我怎样才能确保我已经填入awayTeam_id和homeTeam_id?团队的名字和我从api得到的是一样的。我设置了awayTeam_id和homeTeam_id基于homeTeamName = team.name和awayTeamName = team.name(请参阅query_fixtures方法中的循环)任何帮助,将不胜感激。
不要采取这个人,但我投票结束这个问题,因为虽然这是一个好问的问题,解决方案是非常特殊的问题,并不会广泛适用于其他人。 – smathy