ruby-on-rails - 如何汇总 Ruby on Rails 中连接表中的所有关联记录?

标签 ruby-on-rails ruby activerecord

我的 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/

相关文章:

ruby-on-rails - Carrierwave 条件版本抛出参数错误

javascript - 在服务器失败期间将后备 src 添加到 React 上的图像 (S3)

ruby - 以 10 为增量计算数组中从 1 到 100 的整数

ruby-on-rails - rails : get values of http response

ruby - 如何杀死一个进程及其所有子进程

sql - 如何一步步在rails中查询SQL?

ruby-on-rails - 使用 valid 时跳过特定验证?在事件记录中

ruby-on-rails - rails : HasManyThroughAssociationNotFoundError

ruby-on-rails - 如何在 heroku 中为我的 Saas 应用程序提供自定义域?

ruby-on-rails - 无法安装 json - Ubuntu 14.04 - Rails