Ruby on Rails 3: after destroy method to destroy o

2020-04-10 03:57发布

问题:

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

and

class Role < ActiveRecord::Base

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

end

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.

UPDATE

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?

why is this?

Thanks

回答1:

Maybe you could define the after_destroy callback in the CriticalProcess class. Inside the after_destroy you could then check if the associated Role has zero CP's, and if so, delete the Role.



回答2:

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.