Rails:我应该如何运行我的关联对象?在父级回调之前回调?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查它们是否有效
To check if they are valid