具有附加字段和部分满足的多对多关联的设计模式

Design pattern for many-to-many association with additional fields and partial satisfaction

我正在做一个客户可以获得贷款的项目,该项目将分成 n

客户将付款

class Instalment
  has_and_belongs_to_many :payments
end

class Payment
  has_and_belongs_to_many :instalments
end

他可以支付全部贷款或分期付款,但他的想法是他可以支付任何数量

这意味着部分分期付款将部分支付。

我不确定如何在代码中表达这一点。

例如,客户获得一笔 50 美元的贷款,将分成 5 期,每期 10 美元。客户决定两次支付 25$。

Instalment
--------------
ID | quantity
 1 |      10$
 2 |      10$
 3 |      10$
 4 |      10$
 5 |      10$

Payment 
----------------------
ID | quantity
 1 |      25$
 2 |      25$

Instalments_Payments 
----------------------
payment_id | instalment_id
         1 |             1
         1 |             2
         1 |             3    # note that this instalment_id and next one
         2 |             3    # are the same, but we don't know how much quantity it satisfied in each one.
         2 |             4
         2 |             5

我有两个想法,但我都不喜欢:

在 Instalments_Payments table 中添加两个新字段。一个会标记分期付款是否已全部支付,另一个会标记支付了多少。

Instalments_Payments 
----------------------
payment_id | instalment_id | full_paid | paid
         1 |             1 |      true |  10$ 
         1 |             2 |      true |  10$
         1 |             3 |     false |   5$
         2 |             3 |     false |   5$
         2 |             4 |      true |  10$
         2 |             5 |      true |  10$

添加新模型 PartialPayments,其中付款 has_many :partial_payments

我正在寻找解决此问题的最佳方法。

如果你想要时间效率,那么你应该在数据库中创建一个列 table 记录状态,这将在更好的性能水平上服务于频繁的查询。这是常见的解决方案。

否则,您可以创建一个辅助函数来比较客户应该支付的金额与他已经支付的金额,这会在运行时消耗更多时间。

由于在大多数情况下时间比space更宝贵,我们通常会选择记录状态并在后台异步进行比较,这样用户就不需要等待您的运行时操作完成。因此通常首选第一个解决方案。