Crazy Coders
Crazy Coders

Reputation: 133

Get and sum all association's data

I have 2 models. Company and Orders. Company has many orders. Orders table has a quantity column. I need to fetch orders and sum all quantities belong to each company.

Below code is not working.

class Company < ApplicationRecord
  has_many :orders
  belongs_to :payment_method
end
class Order < ApplicationRecord
  validates :company_id, presence: true
  validates :quantity, presence: true
  belongs_to :company
end
<%  @companies.each do |p| %>
  <p><%=  p.orders.quantity.sum %></p>
<%  end %>

Upvotes: 1

Views: 35

Answers (1)

Jake Worth
Jake Worth

Reputation: 5852

p.orders accesses the associated table. The reason this code isn't working: after getting the associated records, you must iterate over each to add up their quantities.

Here's one way to do that.

p.orders.sum(&:quantity)

Upvotes: 1

Related Questions