ActiveRecord: peer models
What is the best way to relate models as peers?
For example, consider the classic banking example
class Transaction < AR::Base
belongs_to :account
# attribute: amount decimal
end
class Account < AR::Base
has_many :transactions
# attribute name string
end
# move money like this:
t1 = Transaction.create(:amount=>10, :account=>Account.find_by_name('Mine'))
t2 = Transaction.create(:amount=>-10, :account=>Account.find_by_name('Yours'))开发者_开发百科
I want to relate the two transactions so I can go from a particular deposit to the exact withdrawal that is its opposite.
I could add this to the Transaction
model:
belongs_to :mirror_transaction, :class_name=>'Transaction'
has_one :other_transaction, :class_name=>'Transaction', :foreign_key=>'mirror_transaction_id'
... but it feels a bit icky. I can't express it any better than that!
The only other way I can think of is to create a third wrapper model, something like:
class TransactionSet < AR::Base
has_many :transactions
end
Note that I cannot simply extend my Transaction model to relate to both Accounts in one. Some payments go "outside the system" i.e. they will not be paired. Also, in the real-world problem I have, the model is much more complex and I don't want to double everything.
Any advice or other ideas?
TIA!
Vouchers have debit and credit entries. Vouchers also need to be validate that the sum of debits and credits is equal. Voucher Model encapsulates the net transaction. In fact your 2 transactions must be built thru (internally) thru the Voucher (TransactionSet) model itself.
I sharing this with you since i'm working on building a bookkeeping/accounting system myself.
You may pass flags to prevent validations for balancing to not kick off in case certain transaction's pair falls outside of the system.
In the real world, this kind of pairing can be between more than one transaction entry. One debit pairs with 2 credits for example.
I know your question is more technical and apologies if i'm assuming too much but you really need to model your solution around what you have identified as the TransactionSet rather than what you call your icky solution.
精彩评论