Rails: getting an array of values ​​from a model over a period of time

So, I have two models: User and Thing.

User
  has_many :things
end

Thing
  belongs_to :user
end

Thinghas a date associated with it. The user can add zero things one day, and the next 4, and then the day after that, then zero for several days. You get the idea.

Now, what I would like to get is an array of values ​​from the last 7 days. How much has been added by the user? I want to make sure it contains zeros for a few days when nothing has been added. For example, he may return [0, 4, 7, 0, 0, 11, 2].

This is another example of what I'm sure is easy enough to do, but my google-fu is not giving me the opportunity. :-)

Thanks!

+5
source share
2

Rob 7 .

:

things_by_date = user.things.count(:group => 'DATE(created_at)', :conditions => ['DATE(created_at) > ?', 7.days.ago])
(1..7).collect { |d| things_by_date[d.days.ago.to_date.to_s] || 0 }
+2

-

class User < ActiveRecord::Base
  def counts_for_last_week
    (1..7).collect {|i| things.count(:conditions=>["thing_date = ?', i.days.from_now])]
  end
end
+1

All Articles