title: How to query records that are scoped to the most recent record per association
body: <p>I have a <code>Mark</code> model which has many <code>mark_allocations</code></p>
  
  <p>I need to find the number of <code>mark_allocations</code> that are correct, i.e.</p>
  
  <p><code>MarkAllocation.where(status: :correct).count</code></p>
  
  <p>However I only want to query from the most recent mark_allocations per mark.</p>
  
  <p>I have already achieved this in ruby land like so:</p>
  
  <pre><code>MarkAllocation
    .order(created_at: :desc)
    .uniq(&amp;:mark_id)
    .select { |m| m.correct? }
    .size
  </code></pre>
  
  <p>However this has become a performance bottleneck and I would like to do the selection at database level.</p>
  
  <p>So far in my efforts I can get distinct records per mark no problem, but I am struggling to apply an order to get the most recent records per mark. I also have no idea how to go from that point, to further querying for only correct mark_allocations.</p>
  
  <p>I have come up with this:</p>
  
  <pre><code>MarkAllocation
    .select(:mark_id, :state, :created_at)
    .order(created_at: :desc)
    .distinct(:mark_id)
    .where(state: :correct)
    .count(:mark_id)
  </code></pre>
  
  <p>But I know it is not correct and I can see the ORDER clause is missing from the raw sql it outputs.</p>
  
  <p>EDIT:</p>
  
  <p>Here is an example of how it is currently working with the ruby cody.</p>
  
  <pre><code>mark_allocations = [
    {mark_id: 1, status: :correct, created_at: 2.days.ago},
    {mark_id: 1, status: :incorrect, created_at: 1.day.ago},
    {mark_id: 2, status: :correct, created_at: 1.day.ago}
  ]
  
  mark_allocations = mark_allocations.order(created_at: :desc).uniq(&amp;:mark_id)
  =&gt; [  
    {mark_id: 1, status: :incorrect, created_at: 1.day.ago},
    {mark_id: 2, status: :correct, created_at: 1.day.ago}
  ]
  
  mark_allocations = mark_allocations.select { |m| m.correct? }
  =&gt; [{mark_id: 2, status: :correct, created_at: 1.day.ago}]
  
  mark_allocations.size
  =&gt; 1
  </code></pre>