Counting / Aggregation Queries


#1

Hi all,

Suppose you have two models – one for Files and anther for Downloads
– such that a file has_many => :downloads

If you wanted to get a count of the downloads for the current month
and the two previous months, is there a way to get that data from one
query? Something like:

@file.downloads_for_month( 2008, 10 )

where 2008 is the year and 10 is the month…

Thanks!


#2

named_scope is your friend

class Download < ActiveRecord::Base
belongs_to :file

named_scope :between, lambda{ |start_date, end_date| { :conditions
=> [“created_at >= ? AND created_at < ?”, start_date, end_date] } }
named_scope :from_file, lambda { |file| { :conditions => [“file_id
= ?”, file.id] } }
end

Download.between(“2008-10-01”.to_date,
“2008-11-01”.to_date).from_file(file).count