Rails以什么顺序对嵌套父/子模型发生模型回调? [英] Rails in what order do model callbacks happen for nested parent/ child models?

查看:226
本文介绍了Rails以什么顺序对嵌套父/子模型发生模型回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道保存模型的一般顺序是最深的孩子,然后逐渐到父母。但我想知道对于其他回调,是否发生类似的事情:

  ChildA  - 验证之前
ChildB - 验证之前
父级 - 验证之前

ChildA - 验证后
ChildB - 验证后
父级 - 验证后

ChildA - 保存前
ChildB - 保存前
父级 - 保存前

...

或沿以下行:

  ChildA  - 验证之前
ChildA - 验证后
ChildA - 保存前
...

ChildB - 验证之前
ChildB - 验证后
ChildB - 保存前
。 ..

父级 - 验证之前
父级 - 验证后
父级 - 保存前
...
pre>

原因这很重要是因为我有调用属性的调用,并且模型上属性的可调整性取决于其他模型的属性。



例如,我想让 Parent 自动设置 status 属性为完成 if ChildA 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 its status attribute to be Complete if ChildA and ChildB's status attributes are both Complete and the children are both valid.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆