Ticket #33 (closed defect: worksforme)

Opened 1 year ago

Last modified 1 year ago

Clash with has_many :dependent => :destroy

Reported by: rails Assigned to: jcm
Priority: minor Milestone:
Component: plugin Version:
Keywords: dependent Cc:

Description

Many examples for using a scoped better_nested_set will have a two models with a has_many association, like so:

class Foo < ActiveRecord::Base

has_many :bars

end

class Bar < ActiveRecord::Base

acts_as_nested_set :scope => :bar belongs_to :bar

end

Naturally, if a Foo object is destroyed, you would probably like all associated Bar objects to be destroyed as well. Usually, you can set this up in ActiveRecord? by declaring:

has_many :bars, :dependent => :destroy

When I had it set up this way and tried to delete a Foo, it would always throw an exception when trying to destroy the 2nd associated object. This happened because it would call before_destroy on the root node, thus destroying that scope's entire tree. ActiveRecord? would then move on to the next element, not find it, and throw an exception.

A workaround is to add a block to the has_many side of the model, with something like this:

after_destroy do |record|

logger.info('Cleaning up associated better_nested_set') record.bars.root.before_destroy

end

It would be nice to see this taken care of automatically by better_nested_set

Change History

08/14/07 22:11:14 changed by rails

  • status changed from new to closed.
  • resolution set to worksforme.

Have you tried specifying the nested set as follows?

acts_as_nested_set :dependent => :destroy

Note that the default option is :delete_all, but better nested set supports both. Please re-open the ticket if this does not work.

Krishna