class Invoice < ActiveRecord::Base has_many :line_items has_many :payments calculated_attr :subtotal, :dependent => [ :line_items ] do line_items.inject(0) { |sum, line| sum + line.total } end calculated_attr :paid, :dependent => [ :payments ] do payments.inject(0) { |sum, payment| sum + payment.total } end calculated_attr :total, :dependent => [ :line_items ] do subtotal + tax end calculated_attr :due, :dependent => [ :line_items, :payments ] do total - paid end end class LineItem < ActiveRecord::Base end class Payment < ActiveRecord::Base end