Prev | Current Page 52 | 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
# . . . and perform our calculation:
puts "Salary\t\tCount"
Player.calculate(:count, :id, :group=>'salary').each do |player|
salary, count = *player
puts "$#{'%0.2f' % salary}\t#{count} "
CHAPTER 2 n CALCULATING STATISTICS WITH ACTIVE RECORD 25
# Note that the '%0.25f' % call formats the value as a float
# with two decimal points. The String's % operator works
# similarly to the C sprintf function.
end
Save this script as salary_distribution.rb. You can run it as follows:
ruby salary_distribution.rb
Salary Count
$75000.00 1
$75000.50 4
$76000.75 1
$89000.00 1
As you can see, it??™s reasonably trivial to use the calculate function to do simple
grouping and report the results.
Dissecting the Code
Most of Listing 2-2 is code to connect to the database and initialize the models, as you??™ve
seen in other examples.


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