[英]Active record has_many
我需要列出所有用户以及他们通过电子邮件销售的产品总数以及产品总数,
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 user_id 1 1 2 2
OrderItem
id order_id product_id quantity
1 1 1 5
2 1 2 5
2 2 3 5
我需要显示类似名称product_count test@gmail.com 10 test1@gmail.com 5
请尝试以下方法:
OrderItem.includes(:order => :user).group('users.email').sum(:quantity)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.