I'm trying to populate my database table with data from an api. I have three models involved and set up as shown below:
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
To populate the database and making sure I get fixtures for the the league and teams, I used the following code in the Fixture model:
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
However, when I run the code in the rails console, the database gets populated but the awayTeam_id remains blank/null. How can I make sure I get both the awayTeam_id and homeTeam_id populated? The names of the teams and what I'm getting from the api are the same. I'm setting up the awayTeam_id and homeTeam_id based on homeTeamName = team.name and awayTeamName = team.name (Please see loop in query_fixtures method) Any help would be appreciated.