2014-06-25 30 views
2

我有这些模型在我的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 

然而,这个功能感觉很麻烦,我不知道如何可以更加简洁。

感谢您的任何帮助。

+4

你试过'Invoice.where(:id => invoice_ids).sum(:total)'..它应该工作。 –

回答

2

使用您协会(付款已通过拨款许多发票)的设定,你可以简单地这样做:

def invoice_total_of_siblings 
    invoices.sum(:total) 
end 

编辑: 此解决方案,用于开发数据库字段,前提是给定的一组是一个ActiveRecord关联。

然而,在这个特殊情况下,由于它是从评论中产生的,所以total是一个计算字段。因此,给定的集合将不是一个ActiveRecord关联,而是一个Array。然后,您需要映射该字段以便对其进行求和。在这种情况下正确的语法将是:

def invoice_total_of_siblings 
    invoices.sum(&:total) 
end 
+0

啊,是的,谢谢。比我想象的简单得多。不过,我必须用'&:total'来使它工作。我不知道这是为什么。 – Tintin81

+0

你的意思是没有'&'它不工作? –

+1

@ Tintin81您必须使用'&:',因为'invoices'会为您提供'发票'对象的'数组'。 –

相关问题