We have a very simple group and role model
class Group < ActiveRecord::Base
has_many :roles, :dependent => :destroy
end
class Role < ActiveRecord::Base
belongs_to :group
after_destroy :ensure_last_role
private
def ensure_last_role
raise "Can't delete last role" if group.roles.count.zero?
end
end
The after_destroy works perfectly and doesn’t allow the last role to be destroyed by accident. BUT this also prevents the group from being destroyed when :dependent => :destroy tries to destroy all roles. Is it possible to not call ensure_last_role when a group gets destroyed or is there a better way to approach this?
After playing around with this a little while, I settled on a solution that doesn’t use the Rails built in
dependent: :destroyfor the relation, as I couldn’t get the callbacks to fire in the right order. There were also some issues with caching, so each time you try to destroy aRoleit will make a small SQL query to see if its group still exists in the database:At any rate, here’s the full model code: