# Associations, calculate and virtual attributes

**URL:** <https://www.ruby-forum.com/t/associations-calculate-and-virtual-attributes/161454>\
**Category:** Rails\
**Created:** [February 26, 2009, 5:38pm UTC](https://www.ruby-forum.com/t/associations-calculate-and-virtual-attributes/161454 "2009-02-26T17:38:26Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![byrnejb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/d2c977/32.png) [@byrnejb](https://www.ruby-forum.com/u/byrnejb)\
**Post date:** [February 26, 2009, 5:38pm UTC](https://www.ruby-forum.com/t/associations-calculate-and-virtual-attributes/161454/1 "2009-02-26T17:38:26Z")

</div>

I am considering how to approach the problem of providing client  
balances. I have considered treating balances as virtual attributes in  
some fashion approximating this:

class Client \< AR  
…  
has\_many :ar\_transactions, :class =\> ‘Transaction’,  
:conditions =\> { :type =\> ‘ar’,  
:valid? = true }

def balance  
self.ar\_transactions.sum(:balance)  
end

I am also thinking, at the moment, that the balance of a transaction is  
similarly a virtual attribute that might look like this:

class Transaction \< AR  
…  
has\_many :details, :class =\> ‘TransactionDetail’,  
:conditions =\> { :valid? = true, …

has\_many :offsets, :class =\> ‘TransactionJournal’,  
:conditions =\> { …

# I do not account for the separate treatment of debit and credit items

# in this example

def balance  
offset = self.offsets.sum(:amount)  
total - offset  
end

def total  
self.details.sum(:amount)  
end

Is this the way I should do this? Is there a better way?
