我有 2 个模型:
Invoice has_many :lines
Line belongs_to :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 的问题,但我一直无法掌握如何使用它:(
最佳答案
目前尚不清楚您到底想要验证什么,因为您的示例与您之前描述的不同。
我认为这样的东西应该可以工作,使用 before_add callback :
class Invoice < AR::Base
has_many :lines, :before_add => :validate_total
def validate_total(invoice, line)
totals = invoice.lines.sum(:line_value)
if totals + line.line_value > invoice.total
invoice.errors.add(:total, " should be lower or equal to the total amount of the invoice")
return false # I think you can alternatively raise an exception here
end
...
关于ruby-on-rails - 验证部分总和等于父/子记录的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555910/