我需要列出所有用户及其销售的产品总量及其电子邮件和产品总量,
class User < ActiveRecord::Base
# id, location_id, email
has_many :orders, dependent: :destroy
end
class Order < ActiveRecord::Base
#status, payment_mode, total_cost, user_id
has_many :order_items, dependent: :destroy
belongs_to :user
end
class OrderItem < ActiveRecord::Base
# order_id, product_id, quantity,total_price
belongs_to :order
belongs_to :product
end
User
id email
1 test@gmail.com
2 test2@gmail.com
订单 用户 ID 1 1 2 2
OrderItem
id order_id product_id quantity
1 1 1 5
2 1 2 5
2 2 3 5
我需要显示如下 名称 产品数量 测试@gmail.com 10 test1@gmail.com 5
最佳答案
请尝试这个:
OrderItem.includes(:order => :user).group('users.email').sum(:quantity)
关于mysql - 事件记录 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31266826/