Search code examples
ruby-on-rails-3activerecorddependenciesmodel-associations

How to forbid deletion if association present


I have a many to many relationship between two models as follows:

#users.rb
has_many :users_to_roles
has_many :roles, through: :users_to_roles

#users_to_roles.rb
belongs_to :user
belongs_to :role

#roles.rb
has_many :users_to_roles
has_many :users, through: :users_to_roles

I want to disable the deletion of roles if there are users who are "in this role". Here I have found two options who should do the work:

:restrict_with_exception causes an exception to be raised if there are any associated records :restrict_with_error causes an error to be added to the owner if there are any associated objects

but there is no example with the syntax of this and how it should work.

Could you help to make this valid:

#roles.rb
has_many :users_to_roles
has_many :users, through: :users_to_roles, dependent: restrict_with_exception

Solution

  • Such operations can be easily do using Callbacks. In my case, I have added the following method in my model:

    # callbacks
    before_destroy :check_for_users_in_this_role
    
    def check_for_users_in_this_role
      status = true
      if self.security_users.count > 0
        self.errors[:deletion_status] = 'Cannot delete security role with active users in it.'
        status = false
      else
        self.errors[:deletion_status] = 'OK.'
      end
      status
    end