简体   繁体   中英

has_many association with count values

    # == Schema Information
#
# Table name: orders
#
#  id               :integer          not null, primary key
#  order_name           :string(255)
#  payment_mode     :string(255)
#  total_cost       :integer          default(0)
#  user_id          :integer
#  created_at       :datetime
#  updated_at       :datetime
#

class Order < ActiveRecord::Base
  has_many  :order_items, dependent: :destroy
  belongs_to :user
end

# == Schema Information
#
# Table name: order_items
#
#  id          :integer          not null, primary key
#  order_id    :integer
#  product_id  :integer
#  quantity    :integer
#  total_price :integer          default(0)
#  created_at  :datetime
#  updated_at  :datetime
#

class OrderItem < ActiveRecord::Base
  belongs_to :order
end

My expected output should be like order name,total_cost with the count of product of each order.

How can I achieve this using active record.

I tried the following

Order.select("orders.*,count(order_items.product_id) as product_count").joins(:order_items)

Try the following query gives you result as hash and you can achieve your expected result. just verify your relation and table names

OrderItem.joins(:order).select("orders.order_name as order_name,orders.total_cost as total_cost, count(*) as product_count").group(:order_id).as_json

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