Rails以什么顺序对嵌套父/子模型发生模型回调?

编程入门 行业动态 更新时间:2024-10-25 01:26:50
本文介绍了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以什么顺序对嵌套父/子模型发生模型回调?

本文发布于:2023-08-01 09:16:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   嵌套   回调   顺序   以什么

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!