views:

119

answers:

2

I don't know if I'm just looking in the wrong places here or what, but does active record have a method for retrieving a random object?

Something like?

@user = User.random

Or... well since that method doesn't exist is there some amazing "Rails Way" of doing this, I always seem to be to verbose. I'm using mysql as well.

+1  A: 

I'd use a named scope. Just throw this into your User model.

named_scope :random, :order=>'RAND()', :limit=>1

The random function isn't the same in each database though. SQLite and others use RANDOM() but you'll need to use RAND() for MySQL.

If you'd like to be able to grab more than one random row you can try this.

named_scope :random, lambda { |*args| { :order=>'RAND()', :limit=>args[0] || 1 } }

If you call User.random it will default to 1 but you can also call User.random(3) if you want more than one.

aNoble
I've heard RAND() is really slow because it first fetches every record and then somehow chooses one, but I'm probably wrong.
Jorge Israel Peña
@Blaenk: It *is* very slow on MySQL. I do not know about the implementation though.
Swanand
+1 for making a scope, I like that too.
Joseph Silvashy
It also doesn't work on postgres.
Omar Qureshi
+3  A: 

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.

Jorge Israel Peña
This is nice. I like it because it is additionally not ORM specific. Nice work, thanks!
Joseph Silvashy