我有这些模型在我的Rails应用4:如何在Ruby on Rails中通过连接表获取发票的总和?
class Invoice < ActiveRecord::Base
has_many :allocations
has_many :payments, :through => :allocations
end
class Allocation < ActiveRecord::Base
belongs_to :invoice
belongs_to :payment
end
class Payment < ActiveRecord::Base
has_many :allocations
has_many :invoices, :through => :allocations
end
显然,它是可能的一个payment
属于多个invoices
。
在Payment
模式,我有这个功能,总结总数的所有invoices
一个具体的支付涉及到:
def invoice_total_of_siblings
invoice_ids = Allocation.where(:payment_id => id).map(&:invoice_id)
invoices = Invoice.where(:id => invoice_ids)
invoices.to_a.sum(&:total)
end
然而,这个功能感觉很麻烦,我不知道如何可以更加简洁。
感谢您的任何帮助。
你试过'Invoice.where(:id => invoice_ids).sum(:total)'..它应该工作。 –