Story
As a registered user I want to checkout my rank on my profile page and on the leaderboards page
We have user model with name:string, score:integer fields So we need to render user’s rank on the users list and on the user’s profile page based on the score
Wrong way is create rank field in the users table and update it using this awful way
def self.update_ranks self.connection.execute( 'SET @rank := 0' ) self.connection.execute( 'UPDATE users SET rank = ( SELECT @rank := @rank + 1 ) ORDER BY points_sum DESC' ); end
I prefer do not use direct SQL calls We could use this method on the profile page
def rank self.class.all(:order => 'score DESC').index(self) end
# And we could simple render rand based on the index when listing users like
<% @users.each_with_index do |user, i| %> <%= user.name %> <%= @users.offset + i %> # we use will paginate offset collection method <% end %>