Why no :dependent => :destroy on belongs_to?


#1

class Animal < ActiveRecord::Base
belongs_to :species, :polymorphic => true
end

class Goat < ActiveRecord::Base
has_one :animal, :as => :species
end

class Capybara < ActiveRecord::Base
has_one :animal, :as => :species
end

Polymorphic associations here, with goats and capybaras as types of
animals. As usual, there is exactly one Animal record for every Goat or
Capybara record. There should never be an Animal record without a
species-specific counterpart, and vice-versa.

Just as the records are created in pairs, I want them to be deleted in
pairs. If I was always acting on the species, this would be easy. Just
change my models to:

class Goat < ActiveRecord::Base
has_one :animal, :as => :species, :dependent => :destroy
end

class Capybara < ActiveRecord::Base
has_one :animal, :as => :species, :dependent => :destroy
end

and henceforth, myGoat.destroy also accomplishes myGoat.animal.destroy.
But what about the other side of the association? myAnimal.destroy
should accomplish myAnimal.species.destroy. I try:

class Animal < ActiveRecord::Base
belongs_to :species, :polymorphic => true, :dependent => :destroy
end

but the dependent option is ignored. Is there any motivated reason why
belongs_to lacks the :dependent option? Admittedly, the workaround is
really simple:

class Animal < ActiveRecord::Base
belongs_to :species, :polymorphic => true
before_destroy {|animal| animal.species.destroy }
end

but the consistency of the :dependent syntax would be nice.

Also: is there any way to ensure that destroying either half of the
association destroys the whole association? I can only seem to plug the
problem from one side at a time (sending both side’s destroy methods to
each other creates an infinite loop).

A similar previous discussion: http://www.ruby-forum.com/topic/105893