Dec 14, 2007

Selecting random row from a table

I've seen it just too many times. So i must say it. Using SQL query:

select * from table_name order by rand() limit 1;

is not the way to go! It's a performance killer as our poor database server has to generate random number for every row, sort the whole table by it and then just select the lucky row. There is a much better way to solve this, here's how I do it (in RoR):

Model.find :first, :offset => ( Model.count * rand ).to_i

This is much faster than the first method and no custom SQL queries! All this does is count number of rows in a table (very fast) and select one row at some offset while still having the table ordered by primary key (very fast).

Just test the 2 solutions on a large dataset and see for yourself.

Dec 8, 2007

Base Auth is Out!

Hello there, Ruby on Rails fans.

So here it is, my first Ruby on Rails plugin - Best Authorization System Ever. I'm giving you one of the prettiest ways to solve authorization in your applications. A similar solution is already being used in one bigger commercial application and does the job fine so far! You can find out more about it in the README file. If you find this plugin useful, please consider donation (donate button in the right column), so that I have the motivation to improve the plugin :-)

Here's the address to svn repository of the plugin:

http://base-auth.googlecode.com/svn/trunk/

If you have any suggestions/patches/wishes please either contact me by email (robert at aenima dot pl) or simply post a comment.
I hope this plugin will help you as much as it helped me!