0

我正在开发一个可以帮助我跟踪财务状况的应用程序。有一个模型可以跟踪我的投资账户(例如 401k 等)以及与每个账户相关的每月余额。Investment_accounts 模型有_many 余额和余额属于_invest_accounts。

我希望该应用程序现在可以跟踪债务,特别是我的抵押贷款。但我正在努力弄清楚如何最好地建模这个?我需要一个抵押模型,它的信息不同于投资帐户(特别是利率)。但是抵押贷款模型应该利用余额表,因为跟踪抵押贷款余额与跟踪投资账户余额非常相似。但是我不知道如何修改 balances 表以使其足够灵活地同时为mortgage 表和invest_account 表提供服务。

我考虑在 balances 模型上添加一个“type”属性并创建如下命名范围:

scope :investment_accounts, where(type: 'investment')
scope :mortgage, where(type: 'mortgate')

但后来我意识到这应该会导致一些看起来很奇怪的 ActiveRecord 查询。为实例:

investment_accounts.balances.investment_accounts

mortgage.balances.mortgage

我认为这是一种代码气味。关于如何正确执行此操作的任何建议?

4

2 回答 2

1

余额可能只有一些仅在需要时使用的可选字段。或者您可以使用 STI 使 Balance 成为超类,然后为每种类型创建子类。所以你可能有一个 MortgageBalance 和一个 InvestmentAccountBalance 类,其父类是 Balance。它们共享同一个表,有一个类型字段,并允许模型根据其类型进行区分。但我不确定这是否有必要。您可能只能保持松散并使用鸭式打字。mortgage.balances将是为抵押贷款量身定制的余额,甚至可能不需要知道其中的区别。与 Mortgage 对象的关系可能会产生差异。说得通?

于 2013-09-12T03:14:38.397 回答
1

对于polymorphic association.

class InvestmentAccount < ActiveRecord::Base
  has_many :balances, as: :balanceable
end

class Mortgage < ActiveRecord::Base
  has_many :balances, as: :balanceable
end

class Balance < ActiveRecord::Base
  belongs_to :balanceable, polymorphic: true
end

这样,您的余额将有一个balanceable存储类型的列,例如“investment_account”、“mortgage”,可能还有更多。

# Usage
account = InvestmentAccount.last
account.balances

mortgage = Mortgage.last
mortgage.balances

balance = Balance.last
balance.balanceable # Will return object according to its balanceable

有关多态及其迁移的更多信息,请查看指南: http: //guides.rubyonrails.org/association_basics.html#polymorphic-associations

于 2013-09-12T03:12:47.107 回答