【发布时间】:2015-07-07 07:27:45
【问题描述】:
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
我需要列出所有产品及其 order_item 中的数量总和以及它们的总价格总和
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
【问题讨论】:
-
谢谢@jarlh,这可能像 Product.joins(:order_items).sum("order_items.quantity") 吗?
标签: mysql sql ruby-on-rails activerecord