Reputation: 2250
I'm trying to create an array that has the total of all sales a company does for each day of the week. Right now I have something similar to this
@sales = Sale.all
@sales_total = @sales.map{|sale|sale.total.to_i}
Which returns an array of each total for every single sale.
Before turning it into an array, how can I group Sale by day, and adding total together?
Upvotes: 2
Views: 1544
Reputation: 10769
I'm a fan of groupdate gem.
You ca do something like:
@sales_total = Sale.group_by_day(:created_at).order("day asc").sum(:total)
Assuming total
is the column you want to sum up.
EDIT - To add a interval of time condition you can use where
, for example:
@sales_total = Sale.where('created_at between ? and ?', Date.today, 1.week.ago).group_by_day(:created_at).order("day asc").sum(:total)
Upvotes: 3