Rails Scopes: Return record(s) that have maximum cost
<p>I have a <code>Book</code> model which has an attribute of <code>cost</code>.  </p>

<p>I want to write a query that grabs all <code>book</code> record(s) that have the highest <code>cost</code>.  </p>

<p>I need to account for the scenario where more than one <code>book</code> might <em>share</em> the exact same highest <code>cost</code>.  In that scenario, I grab all of those <code>book</code> records that share the highest <code>cost</code> (not just one of them).</p>

<p>Example Datebase for the <code>books</code> table:</p>

<pre><code>id | cost 
 1   4
 2   10
 3   7
 4   20
 5   15
 6   20
 7   3
</code></pre>

<p>so the scope I would need to write would return <em>two</em> <code>book</code> records: the record with the <code>id</code> of <code>4</code>, and the record with the id of <code>6</code>.</p>

<p>I think the answer involves using the <code>maximum</code> method, the <code>having</code> method, and the <code>group</code> method, but I'm having trouble putting all the pieces together for the scope. </p>

<p>Here is one thing I have tried but it doesn't work.  Appears to only return the last record with the highest <code>cost</code> as opposed to <em>all</em> records with the highest cost:</p>

<pre><code>Book.group(:cost).having('books.cost = ?', (Book.maximum(:cost)))
</code></pre>