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()
Written by Randy Morgan
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#