我尝试使用api中的数据填充数据库表。我有三个模型参与并设置如下:
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
为了填充数据库并确保我获得联盟和团队的固定装置,我在Fixture模型中使用了以下代码:
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得到的是相同的。我根据homeTeamName = team.name和awayTeamName = team.name设置了awayTeam_id和homeTeam_id(请参阅query_fixtures方法中的循环)任何帮助将不胜感激。
答案 0 :(得分:1)
if key["homeTeamName"] = t.name
始终为true
,因为您使用了赋值运算符(=
)而不是布尔比较运算符(==
),因此{{} 1}}永远不会被尝试(但出于同样的原因也总是如此)。
答案 1 :(得分:1)
您正在使用错误的流控制逻辑来填充这些字段,这部分:
if key["homeTeamName"] = t.name
homeTeam_id = t.id
elsif key["awayTeamName"] = t.name
awayTeam_id = t.id
end
正在使用=
赋值运算符,它将t.name
的值设置为key["homeTeamName"]
,如果t.name
不是nil
或{{1只有false
才会运行。
除此之外,即使您将运算符更改为正确的homeTeam_id = t.id
相等运算符,==
控制流也只表示if...elsif
或 { {1}}将被设置,永远不会同时设置。
每个homeTeam_id
对象是什么样的? awayTeam_id
是@league.teams
还是t.id
?有homeTeam_id
吗?在awayTeam_id
块内添加t.away_team_id
并发布结果,我将通过更具体的帮助更新我的回答。