Rails 4 - 对相关项目的属性进行求和

时间:2016-01-11 15:24:23

标签: ruby-on-rails activerecord rails-activerecord

我有以下型号:

class Bill < ActiveRecord::Base
    has_many :transactions
end

class Transaction < ActiveRecord::Base
    validates :amount, presence: true, numericality: { only_integer: true }

    belongs_to :bill
    belongs_to :product
end

class Product < ActiveRecord::Base
    validates :name , presence: true, length: { in: 3..20 }

    has_many :transactions, as: :sellable
end

基本上每张账单都有很多交易,销售不同数量的不同产品。

鉴于一组账单,例如Bill.all(但它可能是任何其他子集),我怎么能得到每个产品已售出多少单位的关系?

像...一样的东西。

@sales = {
    product: {id: 1, name: "cream"} , amount: 2,
    product: {id: 1, name: "pencil"}, amount: 23,
    ...
}

2 个答案:

答案 0 :(得分:1)

你需要完全引用Bill,你需要的一切都在你的交易模型中,你应该能够做到:

Transaction.group(:product_id).sum(:amount)

这应该给你类似的东西:

{12: 345, 13: 400, 14: 720}

其中键是product_ids,值是金额的总和

如果您有要查询的帐单子集,则可以使用子查询:

Transaction.where(bill_id: Bill.any_ar_query.pluck(:id)).group(:product_id).sum(:amount)

答案 1 :(得分:0)

您可以创建一个类方法,并将其应用于您拥有的任何ActiveRecord::Relation。像这样:

 def self.sum_by_product
   joins(:product).group(:product_id).sum(:amount)     
 end

然后以这种方式使用它:

Bill.where(status: 'paid').sum_by_product

希望这个帮助