self_with_ancestors is sorting by sort order first rather than depth when order set using default_scope
I've recently turned on sorting on one of my closure_tree'd models using an integer column and suddenly all the breadcrumbs in my site broke.
I've got an integer sort_order column on one of my classes (Capability), which is correctly populated to sort the capabilities within their siblings. The same sort_order value will (of course) appear in different generations and in different branches of the tree, but is unique within any set of siblings. To pull up the breadcrumb trail I retrieve a_capability.self_and_ancestors. Looking at the database access I see it executes:
SELECT "capabilities".* FROM "capabilities"
INNER JOIN "capability_hierarchies"
ON "capabilities"."id" = "capability_hierarchies"."ancestor_id"
WHERE "capability_hierarchies"."descendant_id" = $1
ORDER BY sort_order, "capability_hierarchies".generations asc [["descendant_id", 5262]]
Because this sorts first by sort_order rather than by the depth I don't get the ordered set [self, parent, grandparent, ...] that the documentation implies, instead I get whatever random order their different sort_orders provide. I believe the deterministic sort order should appear after the generations in the ORDER BY clause in this case.
Turns out this is because in the Capability class I added:
default_scope -> { order( 'sort_order' ) }
Without this self_and_ancestors returns the ancestors in appropriate generation order. However without this calling a_capability.children yields the children in a random order, and I don't really want to have to pollute the code with .order(:sort_order)} lots of times. Is there any the closure tree can ensure generational sorting (where required) takes precedence over any other sorting?