I have moved the method to customer model.
joins - for inner join to avoid customers witout order
includes - for eager loading
then sum to return array
class Order < ApplicationRecord | |
belongs_to :customer | |
end | |
class Customer < ApplicationRecord | |
has_many :orders | |
def totals_by_customer | |
Student.joins(:orders).includes(:orders).map { |student| | |
[ student , student.orders.sum(:total) ] | |
} | |
end | |
end |