title: ActiveRecord: efficiently calculating sums
body: <p>I want to display analytics for campaigns. Here is some context:</p>
  
  <ul>
  <li>Campaign statistics are collected by different Companies for specific Ads</li>
  <li>oftentimes, statistics are generated for the same Ad by more than one Company</li>
  <li>statistics are collected in a model called DailyStat</li>
  <li>each campaign involves a number of companies that may or may not be collecting statistics</li>
  <li>campaigns and companies are associated through campaignizations</li>
  </ul>
  
  <p>Campaign -> Ads - > DailyStat</p>
  
  <p>DailyStats belong to both an ad and a company, depending on which company generate the statistics.</p>
  
  <p>The models look as follows:</p>
  
  <pre><code>class DailyStat &lt; ActiveRecord::Base
    attr_accessible :ad, :clicks, :company, :date, :impressions
  
    belongs_to :ad
    belongs_to :company
  end
  
  class Ad &lt; ActiveRecord::Base  
    belongs_to :campaign
    has_many :daily_stats
  end
  
  class Campaign &lt; ActiveRecord::Base
    has_many :campaignizations, :dependent =&gt; :destroy
    has_many :companies, :through =&gt; :campaignizations
  
    has_many :ads, :dependent =&gt; :destroy
  end
  
  class Company &lt; ActiveRecord::Base
  
    has_many :campaignizations, :dependent =&gt; :destroy
    has_many :campaigns, :through =&gt; :campaignizations
  
  end
  </code></pre>
  
  <p>Now, what I want to do most efficiently is:</p>
  
  <ul>
  <li>retrieve a summary of impressions for a specific campaign (by company)</li>
  <li>retrieve a summary of impressions for each ads for a specifc campaign (by company)</li>
  </ul>
  
  <p>Being fairly new to ActiveRecord, I have tried playing around with includes, sums etc., but can't seem to wrap my head around how to get from campaign to company-grouped stats (short of iterating over all ads).</p>
  
  <p>Questions I have:</p>
  
  <ol>
  <li>What would be an efficient approach to tackle this?</li>
  <li>Would it make sense to denormalize and add campaign information to DailyStats?</li>
  </ol>