This whole block is quite hard to read (giant single-line conditionals in particular) and it seems to load thousands of db results into memory. I appreciate that you're not instantiating AR objects, but that's still a lot, and you seem to be iterating over them all multiple times in a request. Did you try creating a SQL-based scope for unpaginated listed taxa like you have elsewhere? If so, what was the problem?