Ruby on Rails: column table column row values ​​based on other column data

I have a table with column identifiers, 'resource_id', 'read_time', 'value', where 'value' is a float

What I'm trying to accomplish is to return a list of records so that the "value" of each record is the sum of all the records in a specific read_time, but it has different values ​​for resource_id.

I am wondering if there is a smart way (i.e. not to iterate over all the records) to accomplish this. I am currently implementing something in this direction:

@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
  end
  aggregate_meter = Meter.new(:read_time => read_time, :value => value, :resource_id => 3)
  @aggregate_meters.push(aggregate_meter)
end

Thanks.

+3
source share
1 answer

ActiveRecord:: Calculate - . , , . , , .

, , .

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

values.each do |read_time, value|
  aggregate_meter = Meter.new(:read_time => read_time, :value => value, :resource_id => 3)
  @aggregates_meter.push(aggregate_meter)
end
+5

Source: https://habr.com/ru/post/1720151/


All Articles