Rails select random record

Most of the examples I’ve seen that do this end up counting the rows in the table, then generating a random number to choose one. This is because alternatives such as RAND() are inefficient in that they actually get every row and assign them a random number, or so I’ve read (and are database specific I think).

You can add a method like the one I found here.

module ActiveRecord
  class Base
    def self.random
      if (c = count) != 0
        find(:first, :offset =>rand(c))
      end
    end
  end
end

This will make it so any Model you use has a method called random which works in the way I described above: generates a random number within the count of the rows in the table, then fetches the row associated with that random number. So basically, you’re only doing one fetch which is what you probably prefer 🙂

You can also take a look at this rails plugin.

Leave a Comment