ruby-on-rails - 如果嵌套关联验证失败,如何允许记录保存事件
问题描述
我有一个模型父母有很多孩子的案例。模型 Child 有一些验证。
在 Parent 模型表单中,我正在使用嵌套属性构建模型 Child 的多个实例。问题是,如果其中一个孩子的验证失败,则整个 Parent 模型不会保存,并且不会创建所有其他有效的孩子。
有没有办法防止这种行为并创建所有有效的关联并默默地失败无效的关联?
我试图删除 inverse_of 选项,但它没有用。
更新:
看来这是不可能的,所以我想出了这个解决方案。我添加了 skip_validation 以避免两次验证关联的记录(一个在 children_attributes= 方法中,另一个在保存时)。
class Parent
children_attributes=(attributes)
super
new_children = self.children.select { |child| child.new_record? }
new_children.each do |child|
if child.valid?
child.skip_validation = true
else
self.children.delete(child)
end
end
end
end
class Child
attr_accessor :skip_validation
validates :attribute, presence: true, unless: :skip_validation?
def skip_validation?
!!skip_validation
end
end
解决方案
推荐阅读
- sas - 在 SAS 中,位于 set 语句之后的冒号是什么意思?
- python-3.x - scikit learn features中的DecisionTree Classifier返回值-2,是什么意思
- machine-learning - 重要性加权自编码器比 VAE 做得更差
- node.js - 我如何为 Postgres 池执行 module.exports
- javascript - 无法从 json 返回的复选框中读取选中的值
- tensorflow - Tensorflow Keras - 将输入并行输入到多个模型层
- javascript - 删除一个类并添加另一个类(在单击时附加 HTML 标记)
- django - 使用 WAMP 和 mod_wsgi 部署 Django restfule 服务
- javascript - 由于文件的加载时间为 5 秒,生产中的 Angular 应用程序加载缓慢
- typescript - 推断 TypeScript 对象和数组的子类型