Ruby on rails 如何在RubyonRails中汇总来自联接表的所有相关记录?
我的Ruby on Rails应用程序中有以下型号:Ruby on rails 如何在RubyonRails中汇总来自联接表的所有相关记录?,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我的Ruby on Rails应用程序中有以下型号: class Invoice < ActiveRecord::Base has_many :allocations has_many :payments, :through => :allocations end class发票:分配 结束 类分配:分配 结束 我的问题是,在分配类中,我希望使用所有关联发票的总金额,最好是在保存回调之前 但是,现在不可能这样做,因为在保存分配对象时,它只与一个特定的发票对象
class Invoice < ActiveRecord::Base
has_many :allocations
has_many :payments, :through => :allocations
end
class发票:分配
结束
类分配
classpayment:销毁
有多张:发票,:至=>:分配
结束
我的问题是,在
分配
类中,我希望使用所有关联发票的总金额
,最好是在保存
回调之前
但是,现在不可能这样做,因为在保存分配
对象时,它只与一个特定的发票
对象关联
如何使用最少的数据库查询来实现这一点
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
有你的total\u amount
方法,这实际上非常简单。
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.sum_allocation_amounts("democol = 'demo params'")