Ferdy
Ferdy

Reputation: 678

has_many with sum active record

class Product < ActiveRecord::Base

      belongs_to  :category
      has_many  :order_items, dependent: :destroy
    end


class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :product
end

I need to list all product with their sum of quantity from order_item and sum of their total_price

Product
id    name
1    product_1

OrderItem
product_id order_id quantity total_price
 1            1      10        200
 1            2      10        200

for example expecting output should be
name       quantity   total_price
product_1  20         400

Upvotes: 3

Views: 321

Answers (4)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

p = Product.first
p.order_items.sum(:quantity)

I hope this may also help

Upvotes: 1

Vishal Jain
Vishal Jain

Reputation: 1940

Try this for active records query. just verify your column,table name and associations you can used like:

   OrderItem.joins(:product).select("products.name as name,sum(total_price) as total_price , sum(quantity) as total_quantity").group("order_items.product_id").as_json

Upvotes: 2

jarlh
jarlh

Reputation: 44766

select p.name, sum(o.quantity) as quantity, sum(o.total_price) as total_price
from Product p
  join OrderItem o on p.id = o.product_id
group by p.name

Upvotes: 2

Mukesh Kalgude
Mukesh Kalgude

Reputation: 4844

Try this query

select a.name,sum(quantity) as quantity ,sum(total_price) as total_price from 
Product a
join OrderItem b on a.id=b.product_id
Group by a.name

Upvotes: 2

Related Questions