This solution is quick and dirty, and might have some performance issues. I'll suggest potential optimizations down below.
Assuming a Product model with the following schema,
# Table name: products
#
# id :integer not null, primary key
# name :string
# amount :float
# quantity :integer
# created_at :datetime not null
# updated_at :datetime not null
in models/product.rb
:
class Product < ActiveRecord::Base
def self.group_by_day
# queries the database
self.all.group_by { |p| p.created_at.beginning_of_day }
# if you're using a different date field, replace 'created_at' with that field.
end
def self.quantity_by_day
# returns an array of hashes, each containing the date and quantity
quantity_array = []
self.group_by_day.each do |day, products|
quantity_array << {
date: day.to_s(:db),
quantity: products.map(&:quantity).sum
}
end
quantity_array
end
def self.group_by_week
self.all.group_by { |p| p.created_at.beginning_of_week }
end
def self.quantity_by_week
# ...
end
def self.group_by_month
self.all.group_by { |p| p.created_at.beginning_of_month }
end
def self.quantity_by_month
# ...
end
end
Product.quantity_by_day.to_json
will give you the data which you can use for the chart. Here's a JSFiddle of a HighCharts chart using the data. (I don't know why the X-axis dates aren't working for me, but the chart shows correctly.edit: fixed it.)
As I mentioned earlier, querying all the products and grouping them in Ruby is inefficient. I would suggest:
Lastly, showing your Products table schema would help us come up with a more specific answer.