Rails:我应该如何运行我的关联对象?在父级回调之前回调?

发布于 2024-11-03 17:57:56 字数 536 浏览 1 评论 0原文

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

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

I have an Invoice model, which has_many :line_items.

Both models have before_validation callbacks. The invoice's callback requires that the line items' callbacks have been run first. However, by default the invoice's callback gets run, then the callback for each line item is run.

Is there a good way ensure that the line items are validated first, then the invoice?

At the moment, I'm toying with something like this:

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

Is there a nicer way to handle this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零時差 2024-11-10 17:57:56

检查它们是否有效

def do_something
  line_items.all?(&:valid?)
  # Then do whatever I need here - I've forced the callback order
end

To check if they are valid

def do_something
  line_items.all?(&:valid?)
  # Then do whatever I need here - I've forced the callback order
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文