Anders
Anders

Reputation: 2941

Delete object in a has_many through relationship with :dependent => :destroy Rails 3.2

Im working on a Rails app where users can create projects. There are two types of users Admins and Collaborators. Both Admins and Collaborators has_many :accounts, through: :account_users, where account_users is a join table. When Admins deletes their accounts, I also want to delete their created account and it's project, but I can't get this to work. My models currently looks like this:

class Collaborator < User
  [...]  
  has_many :account_users
  has_many :accounts, through: :account_users
  [...]
end

class Admin < User
  has_many :account_users
  has_many :accounts, through: :account_users, :dependent => :destroy
  [...]
end 

class Account < ActiveRecord::Base
  [...]
  belongs_to :admin
  has_many :account_users
  has_many :collaborators, through: :account_users
  [...]
end


class AccountUser < ActiveRecord::Base
  belongs_to :admin
  belongs_to :account
  belongs_to :collaborator
end

When a Admin users deletes it's account, only the row in the join table and user table is deleted, their projects isn't deleted.

Note, I use devise for handling authentication.

How could I solve this?

Upvotes: 1

Views: 2753

Answers (1)

Erik Petersen
Erik Petersen

Reputation: 2357

I don't see a project association, so I'm thinking you could do it in one of two ways:

class Account < ActiveRecord::Base
   after_save :destroy_projects

   private
   def destroy_projects
      self.projects.delete_all if self.destroyed?
   end
end

or

class Account < ActiveRecord::Base
  [...]
  belongs_to :admin
  has_many :account_users
  has_many :collaborators, through: :account_users
  has_many :projects, :dependent => :destroy
  [...]
end

Upvotes: 4

Related Questions