2

我有一个Invoice模型,它has_many :line_items

两种模型都有before_validation回调。发票的回调要求首先运行行项目的回调。但是,默认情况下,发票的回调会运行,然后每个行项目的回调都会运行。

有没有一种好方法可以确保先验证行项目,然后验证发票?

目前,我正在玩弄这样的东西:

class Invoice < ActiveRecord::Base
  before_validation :do_something
  ...

private
  def do_something
    line_items.each { |line_item| line_item.run_callbacks(:validation) }
    # Then do whatever I need here - I've forced the callback order
  end
end

有没有更好的方法来处理这个?

4

1 回答 1

1

检查它们是否有效

def do_something
  line_items.all?(&:valid?)
  # Then do whatever I need here - I've forced the callback order
end
于 2011-04-27T11:35:49.883 回答