Prev | Current Page 39 | Next

David Berube

"Practical Reporting with Ruby and Rails"

) The
Win model defines a belongs_to relationship with both the Player and Game models, thus
adding player and game methods to each instance of the Win model. Calling one of these
methods lets you access the particular Player and Game objects with which the Win object
CHAPTER 1 n DATA ACCESS FUNDAMENTALS 15
is associated. The Player model also has an extra method: an instance method called
total_wins, which is used to loop through all of a player??™s wins, returning the total quantity.
This method uses the wins method added by the has_many relationship with the Win
model.
nNote Every time the total_wins method is called, a query is made on the wins table, which could conceivably
take a while. In a production environment, it might be worthwhile to cache the result in the parent
table.
The script loops through each game and finds the player who has the most wins for
that game:
games = Game.find(:all)
games.each do |game|
highest_win=nil
game.wins.each do |win|
highest_win = win if highest_win.nil? or
win.


Pages:
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51