Ruby on Rails 3:如果系统中没有更多相关对象,则在destroy方法之后销毁对象?

我有一点问题,我有以下2个型号:

class CriticalProcess  :destroy has_many :roles, :through => :authorizations after_destroy :check_roles def check roles cp_roles = self.roles cp_roles.each do |role| if role.critical_processes.size == 0 role.destroy end end end end 

 class Role  :authorizations end 

因此,1个角色可以属于许多关键过程,有什么办法可以certificate,如果角色所属的所有关键过程都被破坏,那么它也会被销毁吗? 我需要这个,因为如果要销毁与角色有关系的所有CP(关键进程),那么该角色也应该被销毁,因为它不再需要。

UPDATE

我现在已经创建了一个after_destroy方法,该方法应该删除角色,但这似乎不起作用,由于某种原因,在使用日志调试之后由于某种原因它没有循环通过数组?

为什么是这样?

谢谢

也许您可以在CriticalProcess类中定义after_destroy 回调 。 在after_destroy您可以检查关联的角色是否为零,如果是,则删除角色。

问题是autherization表在调用self.roles之前被删除了,所以我所做的是将after_destroy更改为before_destroy并进行了一些更改,如下所示:

 class CriticalProcess < ActiveRecord::Base has_many :authorizations has_many :roles, :through => :authorizations before_destroy :check_roles def check roles cp_roles = self.roles cp_roles.each do |role| if role.critical_processes.size == 1 role.destroy end self.authorizations.each {|x| x.destroy} end end end 

不是最重要的答案,但它有效,如果有人有更好的答案,请分享。