Skip to content

Instantly share code, notes, and snippets.

@psy-q
Created March 26, 2010 09:00
Show Gist options
  • Save psy-q/344695 to your computer and use it in GitHub Desktop.
Save psy-q/344695 to your computer and use it in GitHub Desktop.
class Account < ActiveRecord::Base
has_many :account_transactions, :as => :debit_account
has_many :account_transactions, :as => :credit_account
def credits
return AccountTransaction.find(:all, :conditions => {:credit_account_id => self.id})
end
def debits
return AccountTransaction.find(:all, :conditions => {:debit_account_id => self.id})
end
def balance
if [Account::ASSETS, Account::EXPENSE].include?(self.type_constant)
# Balances on the credit side of these accounts are total positive
return self.credit - self.debit
else
# Balances on the debit side of these accounts are total positive
return self.debit - self.credit
end
end
end
class AccountTransaction < ActiveRecord::Base
belongs_to :credit_account, :polymorphic => true
belongs_to :debit_account, :polymorphic => true
end
# How come that this is messed up?
# AccountTransaction.new(Account.find_by_name("Bank"), Account.find_by_name("Goods delivered"), 500)
# AccountTransaction.new(Account.find_by_name("Bank"), Account.find_by_name("Foobar"), 200)
# AccountTransaction.new(Account.find_by_name("Foobar"), Account.find_by_name("Bank"), 200)
#
# acc = Account.find_by_name("Bank")
# acc.account_transactions.count # 2 instead of 3!
# acc.credits.count # 2 - correct
# acc.debits.count # 1 - correct
# acc.balance # 500 - correct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment