You can do some of this with ActiveRecord, too. (Note this is my own
little extension so don’t go looking in ActiveRecord documentation for
this particular module.)
module ActiveRecord
module Groups
def groups(columns)
return if columns.empty?
options = columns.last.is_a?(Hash) ? columns.pop.dup : {}
select = columns.join(‘,’) + ',count() AS count_all’
group = columns.join(‘,’)
columns = (columns + [‘count_all’]).map{|c|c.to_s}
find(:all, :select => select, :conditions =>
options.delete(:conditions),
:group => group).map {|rec| rec.attributes(:only =>
columns).values_at(*columns) }
end
end
end
require ‘pp’
pp Booking.count # so the Booking model class will exist
class Booking
extend ActiveRecord::Groups
end
cols = [ :departure ]
result = Booking.groups(*cols)
which gives something like
#=> [ [“AMS”, 3 ], [“BCN”, 1], [“BKK”, 2] ]
or write that out to a CSV file
require ‘fastercsv’
filename = ‘counts.csv’
FasterCSV.open(filename, ‘w’) do |csv|
csv << cols
result.each {|r| csv << r }
end
puts “%5d rows in %s”%[result.size, filename]
Exercises for the reader (the OP, in particular):
look at how the :select option can limit the attributes created in
the model
read how the :group option works on ActiveRecord::Base.find
look at the #attributes method of a model and the Hash#values_at
method