Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Created June 7, 2012 19:45
Show Gist options
  • Save maxjustus/2891131 to your computer and use it in GitHub Desktop.
Save maxjustus/2891131 to your computer and use it in GitHub Desktop.
aggregate arbitrary column on time interval for charts using Postgres and ActiveRecord/Arel
module CountByInterval
def count_by_interval(aggregate_range = 'day', column = "#{self.table_name}.created_at", aggregate_operation = 'count(*)')
aggregate_on = "date_trunc('#{aggregate_range}', #{column})"
self.select_values = ["coalesce(#{aggregate_operation}, 0) as value", "#{aggregate_on} as date"]
ActiveRecord::Base.connection.execute(self.group(aggregate_on).to_sql).collect {|r| r}
end
end
ActiveRecord::Relation.send(:include, CountByInterval) #EWWWWwww
User.where(:in_space => true).count_by_interval('month', 'launched_at', 'sum(body_mass)')
#=> [{"value"=>"7637", "date"=>"2012-04-01 00:00:00"}, {"value"=>"963", "date"=>"2012-05-01 00:00:00"}, {"value"=>"662", "date"=>"2012-06-01 00:00:00"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment