我有以下型號的特性製作一個總:軌道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,
...
}
對不起,我想我沒有正確解釋自己。這個解決方案適用於所有賬單,但如果我想要某個子賬單,這不起作用(例如,'Bill.belonging(customer:「Johnny」)')。我更新了這個問題。 –
這太難了。我瘦我會沿着'Transaction.where(bill_id:Bill.whatever_grouping.pluck(:id))。group(:product).sum(:amount)'的路線走下去。' – Yule
天才!這有效,除了我必須更改':product'爲':product id'。你應該把它添加到主要答案! :)多謝隊友! –