I was able to do this in Rails with recursion:
def add_self_and_children [self, children.sort_by{|e| e.name}.map{|c| c.add_self_and_children}].flatten end
Then call Model.root.add_self_and_children .
But, obviously, this includes a number of massive database calls.
So, if someone knows more about SQL recursion than I want to convert this to pure SQL, that would be magical!
By the way, for some reason, the following, which would be slightly better in the database, did not work:
def add_self_and_children [self, children.order(:name).map{|c| c.add_self_and_children}].flatten end
source share