Prev | Current Page 54 | Next

David Berube

"Practical Reporting with Ruby and Rails"


:database => 'players_3')
# . . . set up our models . . .
class Player < ActiveRecord::Base
has_many :wins
end
class Game < ActiveRecord::Base
has_many :wins
end
class Win < ActiveRecord::Base
belongs_to :game
belongs_to :player
end
def puts_underlined(text, underline_char="=")
# This function will be used to print headers which are underlined
# by an ASCII character such as the equal sign. This makes it
# clear that it's a header and not part of the output data.
puts text
puts underline_char * text.length
end
# . .. and create our report.
# First, we print overall results for each drink:
sql = "SELECT drink,
CHAPTER 2 n CALCULATING STATISTICS WITH ACTIVE RECORD 27
COUNT(*) as total_players,
(SELECT SUM(quantity) FROM wins
WHERE wins.player_id=players.id) as total_wins
FROM players
GROUP
BY players.drink
;"
puts_underlined "Overall"
puts "Drink\t\tWins\tPlayers\tWins/Players"
Player.find_by_sql(sql).each do |player|
puts "#{player.drink.ljust(12)}\t" << # ljust is a function of String
# that ensures the output is always
# twelve characters long, so it lines up
# nicely.


Pages:
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66