Refactor the model associations with proper scopes and joins instead of loops.