我的 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, :dependent => :destroy
has_many :invoices, :through => :allocations
end
我的问题是,在 Allocation
类中,我想使用所有关联发票的 total_amount
,最好是在 before_save
回调中。
然而,现在这是不可能的,因为在 allocation
对象被保存时,它只与一个特定的 invoice
对象。
如何用最少的数据库查询完成这项工作?
最佳答案
Invoice.where(asdfasdfasdf).map(&:allocations).flatten.map(&:total_amount).compact.inject(:+)
因为这是 Rails,所以数据库调用没什么。要总结一组数字,您可以使用这个:
ary = [0,12,2,6,nil]
ary.compact.inject(:+)
#=> 20
你可以稍微清理一下:
class Invoice
#...
def total_amount
allocations.map(&:total_amount).inject(:+) #throws error if there is 1 nil 'total_amount data' value
end
def self.sum_allocation_amounts(sql)
where(sql).map(&:total_amount).inject(:+)
end
end
在 Invoice 类方法中调用 self.map(&:allocations)
是不可能没有错误的,所以我传入了一些基本的 sql 作为解决方法。理想情况下,我可以在 activerecord 的菊花链上直接调用此方法,其中调用 Invoice 但现在对我来说不可行(“类的未定义方法映射”)
Invoice.sum_allocation_amounts("democol = 'demo params'")
关于ruby-on-rails - 如何汇总 Ruby on Rails 中连接表中的所有关联记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24495340/