How do I aggregate activerecord model data for a specific time period?
I'm collecting data from a system every ~10s (开发者_Go百科this time difference varies due to communication time with networked devices). I'd like to calculate averages and sums of the stored values for this activerecord model on a daily basis. All records are stored in UTC.
What's the correct way to sum and average values for, e.g., the previous day from midnight to midnight EST? I can do this in sql but don't know the "rails way" to make this calculation.
Try this:
tz = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)")
range = 1.day.ago(tz.now).beginning_of_day..1.day.ago(tz.now).end_of_day
total = Model.sum(:column, :conditions => {created_at >= range})
精彩评论