title: Rails: How to get all of the records that have the maximum count of a relation with a where clause
body: <p><code>Rails 5.1.2</code></p>
  
  <p>These are the two models in question.</p>
  
  <pre><code>class Person &lt; ApplicationRecord
    has_many :awards
  end
  
  class Award &lt; Application Record
    belongs_to :person
  end
  </code></pre>
  
  <p>The <code>Award</code> model has a column called <code>rank</code> which can be <code>1</code>, <code>2</code>, or <code>3</code>, and a column called <code>category</code> (also integers, but let's just use letters for now).</p>
  
  <p>I'm trying to rank <code>People</code> based on their <code>awards</code> of a certain rank. Many people can have the same amount of a rank. For example, 40 people might have 30 rank 1 awards of category X.</p>
  
  <p>For example:</p>
  
  <h1>Most Awards for Category <code>A</code></h1>
  
  <h2><code>People</code> Granted the <code>Award</code> with <code>Rank</code> <code>1</code> 8 Times</h2>
  
  <ul>
  <li>Person 1</li>
  <li>Person 2</li>
  </ul>
  
  <h2><code>People</code> Granted the <code>Award</code> with <code>Rank</code> <code>2</code> 30 Times</h2>
  
  <ul>
  <li>Person 1</li>
  <li>Person 7</li>
  <li>Person 19</li>
  </ul>
  
  <h2><code>People</code> Granted the <code>Award</code> with <code>Rank</code> <code>3</code> 60 Times</h2>
  
  <ul>
  <li>Person 2</li>
  <li>Person 19</li>
  <li>Person 44</li>
  </ul>
  
  <p>I want to build a query that returns a collection of <code>People</code>.</p>
  
  <p>Logically, this is what my query should do (in pseudo code):</p>
  
  <pre><code>Get all `people` who have the maximum `count` of awards where `awards.category` is `A` and `awards.rank` is `1`.
  </code></pre>
  
  <p>...and repeat this for rank <code>2</code> and rank <code>3</code>.</p>
  
  <p>A counter_cache would not work because of the implication of categories (unless I create a counter_cache for each category, but that feels far redundant and not flexible).</p>
  
  <p>As usual, an idea that sounded simple turned out to be far more complex than I thought, and I have no idea how to pull this off.</p>