Prev | Current Page 38 | Next

David Berube

"Practical Reporting with Ruby and Rails"


Dissecting the Code
First, the script in Listing 1-4 connects to the database, as in the previous example. However,
the models are more complicated than the model in that example, because they
have relationships defined between them and a custom method on the Player model. You
can see those in the following code:
class Player < ActiveRecord::Base
has_many :wins
def total_wins
total_wins = 0
self.wins.each do |win|
total_wins = total_wins + win.quantity
end
total_wins
end
end
class Game < ActiveRecord::Base
has_many :wins
end
class Win < ActiveRecord::Base
belongs_to :game
belongs_to :player
end
The Player model defines a has_many relationship with the Win model, as does the Game
model. This adds a wins method to instances of the Player and Game classes, which can be
used to iterate through the associated wins from either a Player or a Game object. (A savvy
reader will notice from the schema in Listing 1-3 that the Win model is a join table with an
extra attribute, quantity; the quantity attribute is why it is a model in its own right.


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