Rails

How To Get A Records Rank In Rails

Posted by Weston Ganger on November 23, 2015

I wanted to retrieve a users rank in a highscore leaderboard for a game.

Heres the simple way to get the rank.


# Method 1: Quick & Dirty
HighScore.order(:score).all.index(some_user)

# Method 2: Much more efficient by only getting required column
HighScore.order(:score).pluck(:user_id).index(current_user.id)

# Method 3: Fastest Method
User.where("score <= ?", current_highscore).count

If anyone has a less expensive way of performing this operation I would love to hear about it.


Related External Links:


Posted in Rails and Tagged with rails active-record 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts