has_many :autosave =>true 在保存孩子时跳过验证 [英] has_many :autosave => true skips validation when saving children

查看:38
本文介绍了has_many :autosave =>true 在保存孩子时跳过验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 2 和 Rails 3 中,如果 :autosave => true 为 has_many 关联,则循环遍历集合并在每个子关联上调用 save(:validate => false).这是为什么?我们需要一个 before_validation 回调来为该子对象运行,但它不会,因为它是跳过验证的保存.

In both Rails 2 and Rails 3, if :autosave => true a has_many association, the collection is looped through and save(:validate => false) is called on each child association. Why is that? We need a before_validation callback to run for that child object, but it won't since it's a save that skips validation.

有什么好的方法可以解决这个问题?跳过验证的目的是什么?

What's a good way around this? And what is the purpose of skipping validations?

任何帮助将不胜感激!谢谢!

Any help would be much appreciated! Thanks!

推荐答案

Validations do get run.有一个验证阶段和一个保存阶段.AutoSave 尝试同时为两个模型执行这两个阶段.因此,在保存父模型时,将验证父模型,然后验证它的自动保存子模型.验证通过后,保存阶段发生,保存父模型并保存子模型(但跳过验证).原因是因为验证已经运行了.

Validations do get run. There's a validation phase and a saving phase. AutoSave attempts to do these two phases for the two models at the same time. So, upon saving the parent model, the parent model is validated and then it's autosave child is validated. After validations pass, the saving phase happens which saves the parent model and saves the child model (but skips validation). The reason is because the validation has already been run.

我在 before_save 回调期间尝试在父级内部构建子模型时遇到了问题.因此,在验证阶段不需要验证关联的对象.

I was running into a problem when I was trying to build the child model inside the parent during the before_save callback. Therefore the associated object wasn't there to be validated during the validation phase.

这篇关于has_many :autosave =>true 在保存孩子时跳过验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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