Skip to content

Instantly share code, notes, and snippets.

@timurvafin
Created October 13, 2010 14:18
Show Gist options
  • Save timurvafin/624107 to your computer and use it in GitHub Desktop.
Save timurvafin/624107 to your computer and use it in GitHub Desktop.

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 %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment