Have you ever been working on a big awesome website using Ruby on Rails and MySQL and had the need to rank your models by an attribute without loading them all into memory? I know I have.
Unfortunately, unlike Postgres and some other SQL flavors, MySQL lacks a built-in ranking function. After some cursory googling, I found Arjen Lentz’s solution which Chadwick Wood put into use in Rails. However, it’s a little clunky to put all that code in your model for every category you might want to rank, so I DRY’d it up and put together a quick little ActiveRecord plugin to do just that.
It’s easy to use, in your model just declare the columns you want to be able to fetch ranks for:
class User < ActiveRecord::Base rank_by :score end
… and with a little dynamic business you can call a method like this:
@user.score_ranking
So there you go.
I’m willing to bet that this won’t perform well on extremely large datasets, but I haven’t found a better solution for MySQL. For the time being, you probably will want to cache this value somewhere.
You can find out how to install the plugin by visiting Rankitize on GitHub.


