2016-01-11 86 views
1

我有以下型號的特性製作一個總:軌道4 - 對相關ojects

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, 
    ... 
} 

回答

1

你需要引用比爾可言,你需要的一切是你的交易模式,你應該能夠做到:

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) 
+0

對不起,我想我沒有正確解釋自己。這個解決方案適用於所有賬單,但如果我想要某個子賬單,這不起作用(例如,'Bill.belonging(customer:「Johnny」)')。我更新了這個問題。 –

+1

這太難了。我瘦我會沿着'Transaction.where(bill_id:Bill.whatever_grouping.pluck(:id))。group(:product).sum(:amount)'的路線走下去。' – Yule

+0

天才!這有效,除了我必須更改':product'爲':product id'。你應該把它添加到主要答案! :)多謝隊友! –

0

您可以創建一個類的方法和你有什麼ActiveRecord::Relation應用它。就像這樣:

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

然後你以這種方式使用它:

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

希望這有助於

+0

我得到'未定義的方法'事務'爲#'。請記住,事務是對象的屬性,而不是類的屬性。 –

+0

對不起,我的壞!這是一個拼寫錯誤。我會更新我的答案... –

+0

如果你讀了我的問題,我說'賬單的一個子集',而不只是一個。 –