Rails以什么顺序对嵌套父/子模型发生模型回调? [英] Rails in what order do model callbacks happen for nested parent/ child models?
问题描述
我知道保存模型的一般顺序是最深的孩子,然后逐渐到父母。但我想知道对于其他回调,是否发生类似的事情:
ChildA - 验证之前
ChildB - 验证之前
父级 - 验证之前
ChildA - 验证后
ChildB - 验证后
父级 - 验证后
ChildA - 保存前
ChildB - 保存前
父级 - 保存前
...
或沿以下行:
ChildA - 验证之前
pre>
ChildA - 验证后
ChildA - 保存前
...
ChildB - 验证之前
ChildB - 验证后
ChildB - 保存前
。 ..
父级 - 验证之前
父级 - 验证后
父级 - 保存前
...
原因这很重要是因为我有调用属性的调用,并且模型上属性的可调整性取决于其他模型的属性。
例如,我想让
Parent
自动设置status
属性为
完成
ifChildA
和ChildB
的状态
属性都是完成
,子项都是有效
。
我试图用
puts
语句来测试这个语句,但是显然会导致一些奇怪的行为(请参阅此问题:重复多次的嵌套表单验证语句),我恐怕它不具有代表性。
我一定读了Rails指南,但也许我盲目,因为我没有看到引用这里...
解决方案虽然在回调中使用这种状态机逻辑可能是诱人的,难以理解的代码。
这也将有助于数据一致性和测试,如此博文。
I know that the general order in which models are saved is the deepest child first, and then gradually up to the parent. But I'm wondering with respect to other callbacks, does it happen something along the lines of:
ChildA - before validation ChildB - before validation Parent - before validation ChildA - after validation ChildB - after validation Parent - after validation ChildA - before save ChildB - before save Parent - before save ...
OR along the lines of:
ChildA - before validation ChildA - after validation ChildA - before save ... ChildB - before validation ChildB - after validation ChildB - before save ... Parent - before validation Parent - after validation Parent - before save ...
Reason this is important is because I have callblacks that adjust attributes, and the adjustability of an attribute on a model depends on the attributes of other models.
One example is that I want the
Parent
to auto-set itsstatus
attribute to beComplete
ifChildA
andChildB
'sstatus
attributes are bothComplete
and the children are bothvalid
.I tried to test this using
puts
statements, but apparently that leads to some weird behavior (see this question: Nested form validation statements repeating multiple times), and I'm afraid it's not representative.I definitely read the Rails Guides, but maybe I'm blind because I didn't see a reference to this anywhere...
解决方案While putting this kind of state machine logic in callbacks might be tempting, it makes for a hard to understand code. Consider instead having a dedicated method gathering and mutating your data in a more straightforward way.
This would also help with data consistency and tests, as described in this blog post.
这篇关于Rails以什么顺序对嵌套父/子模型发生模型回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!