Rails:如何在由于父级被销毁而被销毁时禁用 before_destroy 回调(:dependent => :destroy) [英] Rails: how to disable before_destroy callback when it's being destroyed because of the parent is being destroyed (:dependent => :destroy)

查看:29
本文介绍了Rails:如何在由于父级被销毁而被销毁时禁用 before_destroy 回调(:dependent => :destroy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班级:Parent 和 Child

I have two classes: Parent and Child with

孩子:

belongs_to :parent

家长

has_many :children, :dependent => :destroy

问题是我想检查总是至少有一个孩子在场,所以我在 Child 中有一个 before_destroy 方法,如果它是属于其父级的唯一孩子,它会中止销毁.

The problem is that I want to check that there is always at least one child present, so I have a before_destroy method in Child that abort the destroy if it is the only child belonging to its parent.

而且,如果我想销毁父级,它会在每个子级上调用 before_destroy 回调,但是当有一个子级时,它会中止销毁,因此父级永远不会被销毁.

And, if I want to destroy the parent, it will call the before_destroy callback on every child, but when there is one child, it will abort the destroy, so the parent will never get destroyed.

我怎样才能告诉孩子只有在它没有因为它的父级而被销毁时才调用 before_destroy 回调?

How can I tell the child to call the before_destroy callback only if it's not being destroyed because of its parent?

谢谢!

推荐答案

has_many :childs, :dependent => :delete_all

这将删除所有子项不运行任何钩子.

This will delete all the children without running any hooks.

您可以在以下位置找到文档:http:///api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

You can find the documentation at: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

这篇关于Rails:如何在由于父级被销毁而被销毁时禁用 before_destroy 回调(:dependent => :destroy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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