How do I sum up records within Rails 3?
I have an ItemsSold model which has the total number of magazines, books, videos, greeting_cards, pens sold for a single day. How do I elegantly return an array with the weekly sold totals for each item for the last arbitrary number of weeks?
I have a model file:
#items_sold.rb
class ItemsSold < ActiveRecord::Base
attr_accessible :magazines, :books, :videos, :greeting_cards, :pens, :sold_date
end
My table is defined as follows:
t.integer :magazines
t.integer :books
t.integer :videos
t.integer :greeting_cards
t.integer :pens
t.d开发者_如何学Goatetime :sold_date
Also, is it possible to return monthly totals for the last year, too?
See ActiveRecord::Calculations#sum
by_week = (1...10).inject({}) do |wh, weeks_ago|
startat = weeks_ago.weeks.ago
endat = (weeks_ago - 1).weeks.ago
wh[weeks_ago] = [:magazines, :books, :videos, :greeting_cards, :pens].inject({}) do |sh, attr|
sh[attr] = ItemsSold.where("sold_date > ? and sold_date <= ?", startat, endat).sum(attr.to_s)
sh
end
wh
end
That will return a hash like {1 => {:magazines => 5, :books => 33, ...}, 2 => {{:magazines => 13, :books => 28, ...}}, ...}
, where each key is a week number (1 for this past week, 2 for two weeks ago, etc..) and the value is another hash with the sums.
精彩评论