Topic: Aggregating statistical data the Rails way

I am trying to calculate some API traffic data for statistic purposes and wondering about the best way to structure this in Rails.

I have a model that tracks the 'received_at' date of a 'Hit'. Hits are create when calls are made to the API in my system.


The SQL for the query I want to run looks like this

 SELECT count(*) total, date(received_at)
   FROM hits
   GROUP BY received_at
   ORDER  total DESC
   LIMIT 1;

Basically counts the hits for each day and returns. BUT this query doesn't return Hit models.

Should I amend the hit model to have a virtual 'Total' attribute?
Should I create a seperate model to aggregate this information? Something like a HitTotal model with a total and date?

What's the Rails way?

Toby Hede
===================================================
FiniteStateMachine - Software Development for Social Networks
===================================================

Re: Aggregating statistical data the Rails way

What exactly do you need to present to the end user? Do you just need to display the number of hits over a period of time?

Railscasts - Free Ruby on Rails Screencasts

Re: Aggregating statistical data the Rails way

Basically, yeah. Couple of other parameters for generating stats, but core function is hits over time ... got it working last night with a virtual accessor for Total on the Hit model.   

The query works fine, I'm just not sure where to put the resulting data.

Toby Hede
===================================================
FiniteStateMachine - Software Development for Social Networks
===================================================

Re: Aggregating statistical data the Rails way

Rails now has an ActiveRecord::Calculations class that lets you do things like minimum, maximum, and sum (documentation for sum) very easily. That should do you nicely.

Last edited by fabio (2007-06-11 03:24:52)

Re: Aggregating statistical data the Rails way

The calculations aren't quite what I am looking for ... I am aggregating counts and grouping the columns, which is not quite the same as sum/max operations.

I think the virtual accessor is enough for the moment and I can refactor it later if I need anything more complex.

Toby Hede
===================================================
FiniteStateMachine - Software Development for Social Networks
===================================================