rails 关联中的自定义验证问题

custom validation issue in rails association

我正在尝试在 rails 关联中添加自定义验证。

financial has_many 关联 payment_milestone

financial有属性year1year2
payment_milestone具有属性 amount.

现在我想要创建多个 payment_milestonefinancialamount 的总数和新创建的 payment_milestone 不应超过 year1+year2 的总数共 parentfinancial

当前代码只检查每个 payment_milestone amount 等于或小于 parent financial year1+year2,同时创建新的 payment_milestones .

payment_milestone.rb

  belongs_to :financial
  validate :cost_head_validation


  def cost_head_validation
    if financial.year1+financial.year2 <=  amount
      errors.add(:amount, "you are exceeding financial cost head")
    end
  end

假设 financialpayment_milestone

之间有 has_many 关系

payment_milestone.rb

def PaymentMilestone < ApplicationRecord
  belongs_to :financial
  validate :cost_head_validation


  def cost_head_validation
    if financial.year1+financial.year2 <=  financial.payment_milestones.sum(:amount) + amount
      errors.add(:amount, "you are exceeding financial cost head")
    end
  end
end

我在这里添加了与财务相关的所有付款里程碑金额以进行验证。希望,它有效。