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
Maybe you could define the
after_destroy
callback in the CriticalProcess class. Inside theafter_destroy
you could then check if the associated Role has zero CP's, and if so, delete the Role.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 abefore_destroy
and made a couple more changes like so:Not the prtiest answer but it works, if anyone has a better answer please share it.