Ruby on Rails 3:如果系统中没有更多相关对象,在destroy方法之后销毁对象? [英] Ruby on Rails 3: after destroy method to destroy object if there is no more related objects in the system?

查看:44
本文介绍了Ruby on Rails 3:如果系统中没有更多相关对象,在destroy方法之后销毁对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,我有以下两种型号:

I have a little problem, i have the following 2 models:

class CriticalProcess < ActiveRecord::Base



  has_many :authorizations, :dependent => :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 < ActiveRecord::Base

  has_many :authorizations
  has_many :critical_processes, :through => :authorizations

end

所以 1 个角色可以属于许多关键进程,我有什么办法可以做到如果 ALL 角色所属的关键进程都被销毁,那么它被销毁还有?我需要这个,因为如果与角色有关系的所有 CP(关键流程)都被销毁,那么角色也应该被销毁,因为它不再需要.

So 1 role can belong to many critical processes, is there any way I can make it that if ALL the critical processes that the role belonged to were to be destroyed, then for it to be destroyed as well? I need this because if all CP's (critical Processes) that the roles had a relationship with were to be destroyed then the role should also be destroyed as its no longer needed.

更新

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

I have now created a after_destroy method which should delete the roles but this doesn't seem to be working, for some reason after debugging using the logs its not looping through the array for some reason?

这是为什么?

谢谢

推荐答案

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

The probelm was that the autherization table was getting deleted before the self.roles was being called, so what i did was i changed the after_destroy to a before_destroy and made a couple more changes like so:

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

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

Not the prtiest answer but it works, if anyone has a better answer please share it.

这篇关于Ruby on Rails 3:如果系统中没有更多相关对象,在destroy方法之后销毁对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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