ActiveRecord_Associations_CollectionProxy 的未定义方法

Undefined method for ActiveRecord_Associations_CollectionProxy

我有几个模型,它们相互关联:

class InsurerPayment < ActiveRecord::Base
  belongs_to :insurer
  belongs_to :company
  has_many :contracts
end

class Insurer < ActiveRecord::Base
  belongs_to :company
  has_many :contracts
  has_many :insurer_payments, dependent: :destroy
end

class Contract < ActiveRecord::Base
  belongs_to :company
  belongs_to :insurer
  belongs_to :insurer_payment
end

当我在 insurer_payments_controller 中执行 commissions = current_company.contracts.pluck(:commission).sum 时,我得到与我当前公司相关的所有合同的佣金总额。但是我需要得到属于我现在公司的保险公司的佣金总额。做类似 commissions = current_company.insurers.contracts.pluck(:commission).sum 的事情会给我一个错误:undefined method `contracts' for # Insurer::ActiveRecord_Associations_CollectionProxy:0x007f92450f79c0。我怎样才能得到我需要的结果?先谢谢了。

你可以试试这个:

current_company.insurers.map { |ins| ins.contracts.pluck(:commission).sum}

您遇到此类错误是因为当您点击 current_company.insurers 时 return 是一个数组,并且您点击了 contracts 在这个数组上这是不正确的。