Search code examples
ruby-on-railssumranking

Ranking position


I have a Rails application with the following models:

  • User
  • Bet

User has many_bets and Bets belongs_to User. Every Bet has a Profitloss value, which states how much the User has won/lost on that Bet.

So to calculate how much a specific User has won overall I cycle through his bets in the following way:

 User.bets.sum(:profitloss)

I would like to show the User his ranking compared to all the other Users, which could look something like this:

"Your overall ranking: 37th place"

To do so I need to sum up the overall winnings per User, and find out in which position the current user is.

How do I do that and how to do it, so it don't overload the server :)

Thanks!


Solution

  • You can try something similar to

    User.join(:bets).
        select("users.id, sum(bets.profitloss) as accumulated").
        group("users.id").
        order("accumulated DESC")
    

    and then search in the resulting list of "users" (not real users, they have only two meaningful attributes, their ID and a accumulated attribute with the sum), for the one corresponding to the current one.

    In any case to get a single user's position, you have to calculate all users' accumulated, but at least this is only one query. Even better, you can store in the user model the accumulated value, and query just it for ranking.