has_many与计数值的关联

时间:2015-07-06 14:55:45

标签: mysql ruby-on-rails activerecord

    # == 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

我的预期输出应该是这样的 订单名称,total_cost以及每个订单的产品计数。

如何使用有效记录实现此目的。

我尝试了以下

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

1 个答案:

答案 0 :(得分:0)

尝试以下查询将结果作为哈希值,您可以实现预期的结果。只需验证你的关系和表名

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