Cache balance in user

This commit is contained in:
Ilion Beyst 2015-09-08 13:09:34 +02:00
parent 334054142c
commit 246492c546
2 changed files with 15 additions and 0 deletions

View file

@ -16,7 +16,16 @@ class Transaction < ActiveRecord::Base
belongs_to :debtor, class_name: 'User'
belongs_to :creditor, class_name: 'User'
after_save :recalculate_balances
after_destroy :recalculate_balances
def client
Client.find_by name: origin
end
private
def recalculate_balances
creditor.calculate_balance!
debtor.calculate_balance!
end
end

View file

@ -20,4 +20,10 @@ class User < ActiveRecord::Base
def transactions
Transaction.where("creditor_id = ? OR debtor_id = ?", id, id)
end
def calculate_balance!
balance = incoming_transactions.sum(:amount) -
outgoing_transactions.sum(:amount)
self.update_attribute :balance, balance
end
end