Relatively new to rails, I’m working on a simple rails app for a few friends to handicap nfl games.
I’m creating an active record model that models information about a sports game, such as home team, visitor, start_time, etc, as well as information related to handicapping that game (favorite, underdog, total, etc).
This feels awkward, becuase for several of these fields I’m basically storing duplicate information (For example, a team is always either a home_team or visitor, and always either a favorite or underdog)
So, my model would look something like this:
create_table "games", :force => true do |t|
t.integer "week"
t.string "home_team"
t.string "visitor_team"
t.string "favorite"
t.decimal "line"
t.decimal "total"
t.string "kickoff"
t.string "status" #['open', 'completed']
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
To keep the model as light as possible I defined only the required fields (home team, visitor and favorite, total) and then I wrote a few simple method in my Game model to return other useful info about the matchup, e.g. instead of listing each team twice in the model (once for underdog/favorite and home/away)
def underdog
teams = [self.home_team, self.visitor_team]
teams.each do |team|
return team if team != self.favorite
end
end
This works, but I was debating whether it made more sense to either create a seperate model for game information (and keep the game model itself minimal) and just use has_many => :through or try some other approach because they way I have my model set up doesn’t seem to feel right storing duplicate information in the same table. Any suggestions or appreciated.
This looks fine to me. In general, you should avoid using has-many-through relationships because they’re messy and complicated and most often unnecessary.
In this case, though, I’d actually recommend creating a
Teammodel. Since it’s the NFL, these teams won’t ever change, but pulling it out lets you reduce the number of strings you need to fill in the database.I’d also refactor the original method:
In Ruby, you do not need to explicitly call
return, as the last statement in your method is implicitly returned. Also, using a loop in this manner in Ruby would be considered bad form.Also, you should take a look at this article on when to use
selfin a model method.