Created
March 26, 2010 09:00
-
-
Save psy-q/344695 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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