Delete Children rails 4

378 Views Asked by At

I have the class project ,

class Project < ActiveRecord::Base
  has_many :Users
  acts_as_tree
end

I want to delete all children, if I delete the parent, in this case meaning, if I delete the project(parent) must be deleted all users (children) and subprojects(children).

I can add by user dependent: :delete_all but I don't know how can I do with acts_as_tree

Thanks

2

There are 2 best solutions below

1
user3506853 On

Try to use dependent: :destroy like:-

has_many :users, dependent: :destroy
0
Ghis On

act_as_tree default behavior will automatically destroy the children when you destroy the parent as you can see in the source code (https://github.com/amerine/acts_as_tree/blob/master/lib/acts_as_tree.rb)

However, you can change this behavior the exact same way as you would with the has_many method, for instance :

act_as_tree dependent: :delete_all

So in your case, you just need to cascade destroy the users :

class Project < ActiveRecord::Base
  has_many :users, dependent: :destroy
  acts_as_tree # dependent: :destroy
end

Therefore @user3506853's answer is actually correct considering the way you present your issue.

Cheers !