我认为您的结构正确,因为特定交易/现金流只能涉及两个账户。如果您使用多对多关联,则需要处理不涉及多于或少于 2 个帐户的验证。对于您当前的结构,您可以将您的模型关联更改为:
class Cashflow < ActiveRecord::Base
belongs_to from_account, :class_name => 'Account', :foreign_key => :from_account
belongs_to to_account, :class_name => 'Account', :foreign_key => :to_account
end
class Account < ActiveRecord::Base
has_many :debits, :class_name => 'Cashflow', :foreign_key => :from_account
has_many :credits, :class_name => 'Cashflow', :foreign_key => :to_account
def cashflows
transactions = []
transactions << self.debits
transactions << self.credits
transactions.flatten!
## or may be the following commented way
# Cashflow.where('from_account = ? OR to_account = ?', self.id, self.id)
end
end
通过这种方式,您可以跟踪特定账户中借记/贷记的金额,并获取参与特定交易/现金流的账户。