Take the 2-minute tour ×

I have a table with columns 'id', 'resource_id', 'read_time', 'value' where 'value' is a float

What I am trying to accomplish is to return a list of records such that the 'value' of each record is the sum of all the records at a specific 'read_time' but having differing 'resource_id' values.

I am wondering if there is a clever way (ie not looping through all the entries) to accomplish this. Currently I am implementing something along these lines:

@aggregate_meters = []
@res_one_meters = Meter.find(:all, :conditions => ["resource_id = ?", 1])

@res_one_meters.each do |meter|
  read_time = meter.read_time
  value = meter.value
  if res_two_meter = Meter.find(:first, :conditions => ["resource_id = ? AND read_time = ?", 2, read_time ])
    value = value + res_two_meter.value
  aggregate_meter = Meter.new(:read_time => read_time, :value => value, :resource_id => 3)

Thank you.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

ActiveRecord::Calculate is your friend here. Letting you do exactly what you want with one database call. It returns a hash using the unique values in the column used in the group as keys.

Here's the code you wrote, rewritten to use sum.

values = Meter.sum(:value, :group => :read_time)

values.each do |read_time, value|
share|improve this answer
Amazing! Thank you very much. I did not know the :group option existed. –  Evan Oct 15 '09 at 7:34
add comment

Your Answer


