Active Record Random

August 30, 2009

Are you looking for a way to select a random record that plays nice with named scope in your Rails app? Throw this into config/initializers/active_record_random.rb:

class ActiveRecord::Base
  def self.random
    if (c = count) > 0
      first(:offset => rand(c)) 

Now you can call random the same way you would call first or all. That means you can do Widget.random to get a random widget or Widget.fancy.random, to get a random fancy widget, assuming you have defined the fancy named scope for Widget.

Posted in Technology | Tags NamedScope, RubyOnRails, Ruby, Rails



Cool hack.

You can also do this:

class ActiveRecord::Base
def self.random
first(:order => 'rand()')

It's simpler and more concise, but depends on the database having a rand() function defined. (Works w/ MySQL; dunno about others.)

# Posted By Joe Grossberg on Monday, August 31 2009 at 4:15 PM



Truth be told I got this from Koz:

He claims doing rand() in the order by is slower.

# Posted By Paul Barry on Tuesday, September 1 2009 at 10:26 AM



I'd still go with clarity over performance, except in the unlikely event this is a bottleneck.

But yeah -- :order => :random -- would be best of all.

# Posted By Joe Grossberg on Wednesday, September 2 2009 at 3:16 PM

Comments Disabled