title: Rails .where query chained to sql function, is there a way to call it on the results without converting them to an array?
body: <p>I have a method that ranks user's response rates in our system called <code>ranked_users</code></p>
  
  <pre><code>   def ranked_users
      User.joins(:responds).group(:id).select(
        "users.*, SUM(CASE WHEN answers.response != 3 THEN 1 ELSE 0 END ) avg, RANK () OVER ( 
          ORDER BY SUM(CASE WHEN answers.response != 3 THEN 1 ELSE 0 END ) DESC, CASE WHEN users.id = '#{
          current_user.id
        }' THEN 1 ELSE 0 END DESC
          ) rank"
      )
        .where('users.active = true')
        .where('answers.created_at BETWEEN ? AND ?', Time.now - 12.months, Time.now)
    end
  </code></pre>
  
  <p><code>result = ranked_users</code></p>
  
  <p>I then take the top three with <code>top_3 = ranked_users.limit(3)</code></p>
  
  <p>If the user is not in the top 3, I want to append them with their rank to the list:
  <code>user_rank = result.find_by(id: current_user.id)</code></p>
  
  <p>Whenever I call <code>user_rank.rank</code> it returns 1.  I know this is because it's applying the find_by clause first and then ranking them.  Is there a way to enforce the find_by clause happens only on the result of the first query?  I tried doing <code>result.load.find_by(...)</code> but had the same issue.  I could convert the entire result into an array but I want the solution to be highly scalable.</p>