This commit is contained in:
benji 2015-09-08 13:36:16 +02:00
commit c38f363dd6
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

@ -21,6 +21,12 @@ class User < ActiveRecord::Base
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
def self.from_omniauth(auth)
where(name: auth.uid).first_or_create do |user|
user.name = auth.uid