Pull out search logic to SearchCandidates
Pull out `s_key` to a method

Also, remove commented out code
Break out with/without permission to methods
Eliminate indentation level by returning early
Fix bad indentation
Eliminate more indentations by breaking early
Use `#joins` instead of separate query
Remove unnecessary condition
Move sorting to AFTER the candidates are collected

Am I missing something here? Seems like sorting it for every iteration was unnecessary and costly.
Move conditional from Ruby to SQL
Fix local variable name change code to one-liners
Move more conditional from Ruby to SQL
Move more Ruby conditional to SQL
And again, move conditional to SQL
DRY up record ordering
Factor out ordering to method, and share it
Use rails4 compatible API
Change `if` to `case`
Pull out assignment
All the reads with `@` are unnecessary