johan
johan

Reputation: 721

How to group items by category and count?

I am doing stats with gem "groupdate", "~> 3.1.1" and gem "chartkick", and I need to know how many items were sold in each category. Here are my models and there associations.

category.rb

has_many :products

product.rb

belongs_to :category, optional: true
has_many :variants, dependent: :destroy

variant.rb

belongs_to :product
has_many :order_items, dependent: :destroy

order_item.rb

belongs_to :variant

I can find the category's title of an order item like so:

OrderItem.last.variant.product.category.title

But how from all the order_items, I can group the categories by title and count?

below is not working of course but that's my try...

def order_item_category
 OrderItem.joins(:variant).product.category.group(:title).count
end

Upvotes: 0

Views: 189

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

You need to join them properly as you need all records

OrderItem.joins(variant: [product: :category]).group('categories.title').count

This should give you the category wise count of the Order Items.

Note: You may also want to add the scope depending on if you only want order items in the completed state.

Upvotes: 1

Related Questions