Working around the ancestry gem's way of object destruction
The ancestry gem 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:
Unfortunately, this does not work as the gem has already put its method
apply_orphan_strategy into the callback chain.
The problem of
The current implementation 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.
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 which will keep this away from your model code.