Forum: Ruby on Rails Counting / Aggregation Queries

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Neal L (Guest)
on 2008-10-21 23: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...

Andrew B. (Guest)
on 2008-10-21 23: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
= ?",] } }

This topic is locked and can not be replied to.