Understanding :dependent => :delete_all?

I can’t see what’s wrong here but that’s probably just because I’m so
new to Rails! To get right into it… I have 4 tables that look like
this:

Sites

  • id

Projects

  • id
  • site_id
  • user_id

Tasks

  • id
  • project_id
  • user_id

Users

  • id

The corresponding models:

class Site < ARB
has_many :projects, :dependent => :delete_all
end

class Project < ARB
belongs_to :site
belongs_to :user
has_many :tasks, :dependent => :delete_all
end

class Task < ARB
belongs_to :project
has_one :user
end

class User < ARB
has_many :tasks
end

The idea is:

  1. If you kill a site you kill all of its projects (this works)
  2. If you kill a project you kill all of its tasks (this works if you
    JUST delete a project but not if you delete an entire site)

I created a single site, then 4 projects and 5 tasks. I then deleted
the site. All of the projects were destroyed, but none of the tasks
were!? What am I doing wrong here?

My controller call to delete a site is pretty rudimentary:
Site.find(params[:id]).destroy

Ideas? Thanks for the help!

Greg

If you use:

:dependent => :delete_all

Then AR will just issue one database command which will delete all
immediately dependent records.

If you use:

:dependent => :destroy

AR will instantiate every dependent record object and call its destroy
method as well (which will honour its :dependent records as well). This
is inefficient in that instead of one DELETE SQL statement for all
records, there is one DELETE for every record destroyed but it will fix
your problem.

If you are dealing with only a few records this will not usually be a
problem but if you are dealing with millions then coding your cascading
delete manually would probably be a better solution.

Great thanks for the response Dave! Much appreciated!