Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 - How to get the row number from a model with an order by
    text
    copied!<p>I am putting together a small app that has a leaderboard concept in it. Basically, the model is just a player_name and a current_score.</p> <p>what I want to do is get the ranking of a specific player, and given that new scores are coming in all the time, it needs to be dynamic. Obviously I could just do a normal find with an order by clause and then I would have to loop through each record. Not very efficient when I could have 100,000's of rows. </p> <p>Any suggestions on what approach I should be taking?</p> <p>Here is the migration for the table:</p> <pre><code>class CreateScores &lt; ActiveRecord::Migration def self.up create_table :scores do |t| t.string :player_name t.integer :current_score t.timestamps end end def self.down drop_table :scores end end </code></pre> <p>EDIT As an example, so I have the following:</p> <pre><code>Score.select('player_name, current_score').limit(20) =&gt; [#&lt;Score player_name: "Keith Hughes", current_score: 9&gt;, #&lt;Score player_name: "Diane Chapman", current_score: 8&gt;, #&lt;Score player_name: "Helen Dixon", current_score: 4&gt;, #&lt;Score player_name: "Donald Lynch", current_score: 9&gt;, #&lt;Score player_name: "Shawn Snyder", current_score: 2&gt;, #&lt;Score player_name: "Nancy Palmer", current_score: 9&gt;, #&lt;Score player_name: "Janet Arnold", current_score: 1&gt;, #&lt;Score player_name: "Sharon Torres", current_score: 9&gt;, #&lt;Score player_name: "Keith Ortiz", current_score: 5&gt;, #&lt;Score player_name: "Judith Day", current_score: 3&gt;, #&lt;Score player_name: "Gregory Watson", current_score: 7&gt;, #&lt;Score player_name: "Jeremy Welch", current_score: 3&gt;, #&lt;Score player_name: "Sharon Oliver", current_score: 7&gt;, #&lt;Score player_name: "Donald Lewis", current_score: 7&gt;, #&lt;Score player_name: "Timothy Frazier", current_score: 7&gt;, #&lt;Score player_name: "John Richards", current_score: 1&gt;, #&lt;Score player_name: "Carolyn White", current_score: 4&gt;, #&lt;Score player_name: "Ronald Smith", current_score: 2&gt;, #&lt;Score player_name: "Emily Freeman", current_score: 9&gt;, #&lt;Score player_name: "Gregory Wright", current_score: 2&gt;] </code></pre> <p>How can I work out the ranking of "Donald Lewis" ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload