Last Updated: February 25, 2016
·
1.841K
· randym

Quick Ranking by attribute Rails/Heroku

Need to rank your users by a specific attribute?

window functions for the win!
http://www.postgresql.org/docs/8.4/static/functions-window.html

Make sure you enable heroku-postgresql:basic addon and we are talking milliseconds for thousands of users.

class User < ActiveRecord::Base

  def self.update_ranking
    sql = "update users
              set rank = d_rnk
              from (SELECT id, row_number() OVER (ORDER BY total_downloads DESC) as d_rnk FROM users) as ranked
             where ranked.id = users.id;"
     self.transaction do
       ActiveRecord::Base.connection.execute(sql)
     end
  end
end

rank(), deep_rank()