Reputation: 27852
I have the following situation:
I have a Club which can have several Teams, and a Team can have several Players.
However, the Players that a Team has will vary each year. I am wondering how could I put somehow season information into the picture in a way that the user will be able to add/remove Players each season and be able to see Players of a team from previous seasons.
So, given the following models:
Club has_many Team
Team belongs_to Club
Team has_many Players
How would I make it so that Team has_many Players depends on the Season (2013/2014 - 2012/2013..)
Upvotes: 0
Views: 469
Reputation: 525
There are two ways to do it:
One is to create another relation for the SEASON
and create a ternary relationship (http://www.databasedesign.co.uk/bookdatabasesafirstcourse/chap3/chap3.htm)
The tables would look something like this:
PLAYER(id,...)
TEAM(id,name,...,club_id)
SEASON(id,season_name,...)
SEASON_PARTICIPATION(id,player_id,season_id,team_id)
And the ActiveRecord associations would be:
class Club < ActiveRecord::Base
has_many :teams
end
class Team < ActiveRecord::Base
belongs_to :club
has_many :players, through: :season_participations
end
class Player < ActiveRecord::Base
belongs_to :teams, through: :season_participations
end
class Season < ActiveRecord::Base
has_many :players, through: :season_participations
end
class SeasonParticipation < ActiveRecord::Base
belongs_to :player
belongs_to :team
belongs_to :season
end
More documentation on ActiveRecord
associations can be found here: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
Another way of doing this is to skip the SEASON
relation all together and have it as a simple attribute in the SEASON_PARTICIPATION
relation. So instead of a season_id
you would have the name of the season in the SEASON_PARTICIPATION
(see diagram 2). Having a separate SEASON
relation gives you the opportunity to store more information about the season, like start-date/end-date etc. Eventually you could also add division information in another relation.
Upvotes: 4
Reputation: 365
There's many ways you could do this. Here's a few that spring immediately to mind.
Upvotes: 0