I'm trying to setup a sample application that tracks football matches. There's currently 3x tables:
- Ground - The home ground of a particular team
- Team - The actual team itself
- Game - A game, which will hold two teams
I can successfully query "Which two teams are playing in this game?", but I'm struggling to reverse it and ask "Which games has this team played in?"
I've setup a new rails project, with Rails 5.1.7 and been using the Rails console to query the data.
Migrations
Ground
def change
create_table :grounds do |t|
t.string :ground_name
t.string :ground_location
t.belongs_to :team
t.timestamps
end
end
end
Game
def change
create_table :games do |t|
t.timestamps
t.datetime :game_time
t.belongs_to :team_one
t.belongs_to :team_two
end
end
end
Team
def change
create_table :teams do |t|
t.string :team_name
t.timestamps
end
end
end
Models
Ground
class Ground < ApplicationRecord
belongs_to :team
end
Game
class Game < ApplicationRecord
belongs_to :team_one, :class_name => "Team"
belongs_to :team_two, :class_name => "Team"
has_many :teams
end
Team
class Team < ApplicationRecord
has_one :ground
end
I can successfully query:
g1 = Game.new
g1.team_one = Team.first
g1.team_two = Team.second
g1.save
Game.first.team_one -> Correctly spits out team
Game.first.team_two -> Correctly spits out team
I'd like to be able to get a list of games for a team:
Team.first.games
Team Load (0.0ms) SELECT "teams".* FROM "teams" ORDER BY "teams"."id" ASC LIMIT ? [["LIMIT", 1]]
NoMethodError: undefined method `games' for #<Team:0x5a53fa0>
from (irb):1
I'm definitely missing something, but would hope this is possible. If anyone could shed any light on this, I'd really appreciate it! Thanks in advance.