Forum: Ruby on Rails Counting / Aggregation Queries

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bbf55d9960b9905e57621d5da6727b2d?d=identicon&s=25 Neal L (Guest)
on 2008-10-21 21:08
(Received via mailing list)
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!
6fabb84e727dee98d1277df56458cbac?d=identicon&s=25 Andrew Bloom (Guest)
on 2008-10-21 21:54
(Received via mailing list)
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
This topic is locked and can not be replied to.