WIP
Refactoring to make it more understandable.
Using more activerecord instead of pure sql.
Fix issue where count queries would explode.

Only applied to Rails master branch.
Fix unnecessary initialization of default permission set when it wasn't being used.