I have a table named stats made up of two important columns ‘stat_type’ and ‘count’. We run a rake task which populates TaskBin related statistics at the end of every day into the stats table. Column count holds count of users signed up per day is stored.

To generate the report, I fire the query from my controller action as

@stats = Stat.find(:all, :conditions => ["stat_type = 'signup_confirmed'"])

These model objects(@stats) are stored as per day basis. Now, I need to display the @stats grouped by month and grouped by week. Rails enumerable class has a method called group_by which is very super-powerful and allows us to group, active record objects by a passed parameter.

So here is the code which I wrote.

Add the following methods in model ( in Stat model),

def week
  self.created_at.strftime("%W")
end

def month
  self.created_at.strftime("%y%m")
end

Now just add following two magical lines in same controller action

#returns a hash, with key as week number and value as grouped results as array.
@weekly_stats = @stats.group_by(&:week) 
@monthly_stats = @stats.group_by(&:month)

(one point, use of &: is dangerous as pointed out by Pratik, you can use @stats.map{|i| i.week} and @stats.map{|i| i.month } instead of &: symbol.

And your view code will look similar like this (shown for week only).

<% @weekly_stats.each do |week, stats| %>
  <tr>
    <td>
      Week <%= week %>
    </td>
    <td>
      <% count_array = stats.collect{|i| i.count}%>
      <%= count_array.sum %>
    </td>
  <tr>
<% end %>

I hope you enjoyed this simple trick. Do comment if you have other tricks/suggestions. Keep tasking. visit TaskBin.com.