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 :debtor, class_name: 'User'
belongs_to :creditor, class_name: 'User' belongs_to :creditor, class_name: 'User'
after_save :recalculate_balances
after_destroy :recalculate_balances
def client def client
Client.find_by name: origin Client.find_by name: origin
end end
private
def recalculate_balances
creditor.calculate_balance!
debtor.calculate_balance!
end
end end

View file

@ -21,6 +21,12 @@ class User < ActiveRecord::Base
Transaction.where("creditor_id = ? OR debtor_id = ?", id, id) Transaction.where("creditor_id = ? OR debtor_id = ?", id, id)
end end
def calculate_balance!
balance = incoming_transactions.sum(:amount) -
outgoing_transactions.sum(:amount)
self.update_attribute :balance, balance
end
def self.from_omniauth(auth) def self.from_omniauth(auth)
where(name: auth.uid).first_or_create do |user| where(name: auth.uid).first_or_create do |user|
user.name = auth.uid user.name = auth.uid