To retrive a random row from a table you have do just this:

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

This is fast and requires no custom SQL queries! All this does is count number of rows in a table and select one row at some offset while still having the table ordered by primary key.

It uses offset (limit), not ID number, so it chooses n-th found row, not a row with ID equal to n. So if you have IDs like 1, 2, 4, 8and get 3 at random, this method will take 3rd row, which has ID = 4.

blog comments powered by Disqus

Recently


(function() { var links = document.getElementsByTagName('a'); var query = '?'; for(var i = 0; i < links.length; i++) { if(links[i].href.indexOf('#disqus_thread') >= 0) { query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&'; } } document.write('