I have invoices that are made up invoice items. Each item has a profit and I want to sum these up and store the total profit at the invoice level.
Previously I was doing this calculation on-the-fly, but to improve performance I now need to store this value in the database.
class InvoiceItem < ActiveRecord::Base
belongs_to :invoice
end
class Invoice< ActiveRecord::Base
has_many :invoice_items
def total_profit
invoice_items.sum(:profit)
end
end
I want the total_profit to always be correct, so it needs to be updated whenever an invoice item is added, edited or deleted. Also the total_profit probably should be protected from being directly edited.