This is looks interesting! Is this task safe to run on an existing site?
After some fiddling in the rails console, I once ended up with an install where topic counts were wrong (e.g. an empty category claimed to have 10 topics in it) and manually wrote code to fix this (see # update all topic counts
in the post linked above). It sounds like this rake task would probably solve issues like this