ruby-on-rails - 验证部分总和等于父/子记录的总和

标签 ruby-on-rails ruby-on-rails-3 validation associations

我有 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

但是

  1. 它不适用于新对象(仅更新)
  2. 即使是更新,它也会系统地抛出错误

我还看到过一个关于 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/

相关文章:

ruby-on-rails - 无法从命名的 javascript 函数访问元素

ruby-on-rails - 如何传递 ransack 参数 [ :q] object to another method in rails

c# - 当 WPF 中的文本更改时对 TexBox 强制执行验证

qt - 禁用 QSpinBox 中的验证

ruby-on-rails - 请求的资源上不存在 'Access-Control-Allow-Origin' header

javascript - Rails link_to 忽略 e.preventDefault();来自 jQuery 调用,因为方法 : :get is set

html - 如何在 Rails 中使用自定义样式覆盖 Bootstrap 样式

jquery - .autocomplete 不是一个函数

mysql - 使用 Rails 3 的报价生成器应用

Java参数验证,文件存在,可以读取并且是常规文件