How To Get A Records Rank In Rails
Posted by Weston Ganger
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: