Working around the ancestry gem's way of object destruction

Posted . Visible to the public.

The ancestry gem Show archive.org snapshot allows you to easily use tree structures in your Rails application.

There is one somewhat unobvious pitfall to it: its way of applying the orphan_strategy which defines how it handles children of an object going to be destroyed.

What's this all about?

In many cases you might want to disallow destruction if there are any child nodes present. The restrict strategy does the trick but raises an exception when destroy is called:
has_ancestry :orphan_strategy => :restrict

One solution seems to be to prevent destruction by adding a check to the callback chain of destroy, either by a custom method or like that:
before_destroy :is_childless?

Unfortunately, this does not work as the gem has already put its method apply_orphan_strategy into the callback chain.

The problem of apply_orphan_strategy

The current implementation Show archive.org snapshot of this method does not add any errors or return false to prevent destruction -- it either raises an exception (for restrict) or destroys or moves all children, depending on your strategy.

If you tried to apply your own way you might not have set one which means the default: deletion of all child nodes before your method is even called.

Solution

Disable the gem's method by overwriting it:

def apply_orphan_strategy
  # Destruction will be handled separately.
end

You might package that (including a method adding errors) it into a neat trait Show archive.org snapshot which will keep this away from your model code.

Martin Straub
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Martin Straub to makandra dev (2010-10-15 12:37)