mchapman17
mchapman17

Reputation: 53

database structure for league application

first post on SO so I apologise if I'm not following the guidelines correctly.

I am designing an online league management application in Rails and have come across some issues in the database design which I'd rather sort out now than go ahead with what I've got and find out it's not going to work later.

Currently I have the following models:

class League < ActiveRecord::Base
    has_many :teams
    has_many :players
end

class Team < ActiveRecord::Base
    belongs_to :league
    has_many :players
end

class Player < ActiveRecord::Base
    belongs_to :league
    belongs_to :team
end

The idea is that league can either be made up of teams of players, or just individual players without a team. I have currently have a league_type attribute in the Leagues table which identifies whether the league is for teams or players. My first question is whether or not this is a good way to handle this situation?

One of the reasons this seems like it may be a problem is when I try to create a match, because it will either be made up of players or teams. I originally thought I'd have a Match model with home_id and away_id attributes, and then populate those with either player_ids or team_ids depending on the league type, however that doesn't feel like good design to me. I've considered making the home and away fields polymorphic, perhaps that's the best way? Eg.

class Match < ActiveRecord::Base
    belongs_to :home_matchable, polymoprhic: true
    belongs_to :away_matchable, polymoprhic: true
end

And then adding "has_many :home_matches, as: home_matchable" and "has_many :away_matches, as: away_matchable" to Teams and Players.

I'm finding just with the limited number of views and controllers I have at the moment, I seem to be needing to regularly check whether the league is for teams or players, so there's a lot of "if league_type == 'teams' do something else do something else" statements in my code which feels a bit ugly. Especially if down the track I decide I want to add a "doubles" type for example, so they would turn into "if 'teams' then else if 'players' then else" etc.

Sorry this turned out a lot longer than I expected, any help is much appreciated!

Upvotes: 2

Views: 364

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10405

Why not force a player to be in a team by default? When creating a player in DB, you'd automatically create a team for him and make him the sole member.

You could also mark these teams with a boolean telling you these are not multi-player teams.

This way, you'd only deal with teams when creating Matches. I personally don't like the polymorphic approach, it can become tricky to manipulate different Models while accessing your associations.

Upvotes: 1

Related Questions