Database modeling

I have a player model and a game model set up with a HABTM.

I am trying to keep track of statistics for a player based on a hits
and misses, which the user marks when editing a game. When the game is
done editing an email is sent to the other team to confirm the game.
If it is confirmed the statistics should be updated on the site.
Here’s what I have:

def confirm_game
@games = Game.find(:all)
for game in @games
if (found the right game through hashing)
game.update_attribute(:confirmed, true)
game.update_statistics
flash[:notice] = “Thank you for validating the game.”
break
end
end
end

Game model
def update_statistics
for team in self.teams
for player in team.players
player.update_statistics(self)
end
team.update_statistics
School.find(team.school_id).update_statistics
end
end

Player Model
def update_statistics(game)
for player in @game.players
self.update_attribute(:hit_percentage, (player.hit.to_f /
(player.hit.to_f + player.misses.to_f)) * 100) unless player.misses ==
0
self.update_attribute(:opp_percentage, player.points.to_f /
(player.hit.to_f + player.misses.to_f)) unless player.misses == 0
end
end
end

def add_hit
self.update_attribute(:hit, hit + 1)
end

I don’t think this is the correct way to represent each hit a player
has per game. How do I set it up like that?
Also how do I write a view to show the game with each player’s hits/
misses?

I am not sure that your present approach with respect to the data is
sound. Generally, statistics are derived and updated from accumulated
raw data. What might prove more beneficial in the long run is to simply
store each player’s raw performance. So, assuming baseball as the sport,
one could store this information in the GamePlayer model.

Something like this (NOT TESTED)

class Player

has_many :player_game_stats, :class_name => ‘GamePlayer’
has_many :player_games, :class_name => ‘GamePlayer’, :include
=> :game
has_many :games, :through => :player_games

class Games

has_many :game_players, :include => :player
has_many :line_ups, :class_name => ‘GamePlayer’
has_many :players, :through => :game_players

class GamePlayer

belongs_to :player
belongs_to :game

with model attributes / db columns:
player_id
game_id
position_played
innings_played
batting_order
at_bats
strike_outs
base_on-errors
walks
singles
doubles
triples
hr
rbi
… and so forth.

Then you simply derive your statistics from the detailed records in
player_games. This can be done at the DBMS level using stored procedures
in many cases thus simplifying your application even further.