Question

How do I get a hash with the number of objects in a class for each week, i.e. Objects per week?

If there are no objects present for a week it should return 0.

I'd also like to return the start date of each week, entries span 2009-10-01 to 2011-5-18, but will be updated. I'm looking for a little function I can call on @objects, which will be different counts depending on the scope of dates requested.

I have a feeling the rails sum() method will be useful, but I'm not sure how to ask by week.

I hope that's clear :) Thanks in advance

Was it helpful?

Solution

Try:

Hash[
  Quote.count(:id, group: :created_at).group_by {|k,_| 
    k.beginning_of_week 
  }.map { |week, ary| 
    [week, ary.map(&:last).sum]
  }.sort_by &:first
]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top