我有2种型号:验证该部分的总和等于与父母总/儿童记录
Invoice has_many :lines
Line belongs_to :invoice
我想确保Line
对于给定Invoice
比赛总的总和相关的Invoice
。
我已经试过这样:
validate :total_amount
def total_amount
inv_id = self.invoice_id
target_amount = Invoice.find(inv_id).total
total_lines = Line.where(invoice_id: inv_id).sum(:line_value)
errors.add(:total, " should be lower or equal to the total amount of the invoice") if total_lines > target_amount
end
但
- 它并不适用于新的对象(只更新)工作
- 甚至更新系统地抛出一个错误
我也看到一个关于AssociatedValidator的问题,但我还没有能够掌握如何使用:(