Basically you need to join tables categories, products, order_itemsand orders.
The connection can be made using the following code:
rel = Category.joins(products: [order_items: :order])
#=> SELECT "categories".* FROM "categories" INNER JOIN "products" ON "products"."category_id" = "categories"."id" INNER JOIN "order_items" ON "order_items"."product_id" = "products"."id" INNER JOIN "orders" ON "orders"."id" = "order_items"."order_id"
Based on this, you can filter the date range.
, d1 d2, :
rel = rel.where('orders.placed_on >= ? AND orders.placed_on <= ?', d1, d2)
:
result = rel.select('categories.id, categories.name, SUM(order_items.qty) as qty, SUM(order_items.qty * order_items.price) as total')
.group('categories.id, categories.name')
sample = result.first
sample.id # => 1
sample.name # => "Category 1"
sample.qty # => 100.0
sample.total # => 500.0