Forum: Ruby on Rails associations, calculate and virtual attributes.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
James B. (Guest)
on 2009-02-26 18:38
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

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

def total

Is this the way I should do this?  Is there a better way?
This topic is locked and can not be replied to.