Reputation: 1433
I have several models, which are connected to each other:
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
When I do commissions = current_company.contracts.pluck(:commission).sum
in my insurer_payments_controller, I get the sum of commission for all the contract related to my current company. But I need to get the sum of commission that belongs to insurers of my current company. Doing something like commissions = current_company.insurers.contracts.pluck(:commission).sum
gives me an error: undefined method `contracts' for # Insurer::ActiveRecord_Associations_CollectionProxy:0x007f92450f79c0. How can I get the result I need? Thanks ahead.
Upvotes: 0
Views: 1182
Reputation: 1440
You can try this:
current_company.insurers.map { |ins| ins.contracts.pluck(:commission).sum}
You are getting this type of error because when you hit current_company.insurers
is return an array, and you hit contracts on this array this is incorrect.
Upvotes: 1