I'm developing an application to schedule soccer matches for two teams at a time. So, for example I need to schedule a match for two teams, but I'm not sure how can I structure the database relation between these two entities.
One solution I thought is a relation many to many between them, and in the Associative Table(match_teams) I put a is_visitor field, to indicate which team is playing outside home:
team model:
class Team < ApplicationRecord
has_many :match_team
has_many :matches, through: :match_team
end
match model:
class Match < ApplicationRecord
has_many :match_team
has_many :teams, through: :match_team
end
match_team model:
class MatchTeam < ApplicationRecord
belongs_to :match
belongs_to :team
end
team migration:
class CreateTeams < ActiveRecord::Migration[5.1]
def change
create_table :teams do |t|
t.timestamps
end
end
end
match migration:
class CreateMatches < ActiveRecord::Migration[5.1]
def change
create_table :matches do |t|
t.timestamps
end
end
end
match_teams migration:
class CreateMatchTeams < ActiveRecord::Migration[5.1]
def change
create_table :match_teams do |t|
t.belongs_to :match, index: true, foreign_key: true
t.belongs_to :team, index: true, foreign_key: true
t.boolean "is_visitor", default: false
t.timestamps
end
end
end
So, I can do something like:
#create team here
#create team2 here
match = Match.new()
match.teams = [team, team2]
match.save!
match_team_associative = match.match_team
match_team_associative.each do |item|
if item.team_id == team.id
item.is_visitor = true
item.save!
end
end
I don't know if this is the better solution, or if it's ok the manner I'm changing the value of is_visitor field in the associative table.
Another soluction I think would be has two relations one to many between these entitties team and match. A table matches would have a foreign key for teams called team, and another foreign key for teams called visitor_team, like:
matches table:
id | team | visitor_team
1 | 1 | 2
But this second soluction I could't implement, I don't know how to do that. I find something here but I could't make it work. Does anyone can help me telling me how to make it work that way?
Which of these two solution is better? I think maybe the second, but it couldn't make it work.
I appreciate any help.
Thank you.