我的 Rails 4 应用程序中有这些模型:
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
显然,一笔付款
可能属于多张发票
。
在付款
模型中,我有一个函数,可以对与一笔特定付款相关的所有发票
的总和进行求和:
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
但是,这个函数感觉很麻烦,我想知道如何让它变得更简洁。
感谢您的帮助。
最佳答案
使用您的一组关联(付款通过分配有许多发票),您可以简单地执行以下操作:
def invoice_total_of_siblings
invoices.sum(:total)
end
编辑:
该解决方案按原样适用于数据库字段,前提是给定的集是 ActiveRecord 关联。
然而,在这种特定情况下,由于它是根据注释生成的,因此 total
是一个计算字段。因此,给定的集合将不是 ActiveRecord 关联,而是数组。然后,您需要映射该字段才能对其求和。在这种情况下,正确的语法是:
def invoice_total_of_siblings
invoices.sum(&:total)
end
关于ruby-on-rails - 如何在 Ruby on Rails 中跨联接表获取发票总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24404169/