views:

389

answers:

3

I'm doing some statics calculation in my product. A user has performed a number of operations, let's say posted comments. I want to be able to show them how many comments they've posted per week for the past month, or per month for the past year.

Is there any way with activerecord to group this way? Is my best best to simply do this manually - to iterate over the records summing based on my own criteria?

class User < ActiveRecord::Base
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :user
end

@user.comments(:all).map {|c| ...do my calculations here...}

or is there some better way?

thanks! Oren

A: 

My guess would be something like:

@user.comments.count(:group => "month(created_at)")

Dry-code, ymmv

fd
I believe this will group by month across years as well - so if you've got two years of data, all stuff in January year 1 and year 2. What I'm looking for is a way of telling for a 24 month window for example, how many per month.
teich
You could add a condition to limit the year also, like :conditions => [:created_at, "> #{24.months.ago}"]. Again, untested, but should be possible with something like this.
fd
A: 

Check out the has_activity plugin.

Jim Gilliam
Thanks for the pointer. Looks like has_activity is mysql only. My production host is postgresql.
teich
A: 

In this case, the best solution for me was to either do it in straight SQL, or to use the activerecord group_by function:

@user.all.group_by{ |u| u.created_at.beginning_of_month }
teich