简体   繁体   中英

Active record has_many

I need to list all user with their total product sold by them with their email and the product total quantity,

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

Order 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

I need to display like name product_count test@gmail.com 10 test1@gmail.com 5

请尝试以下方法:

OrderItem.includes(:order => :user).group('users.email').sum(:quantity)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM