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))
end
end
end
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
.
Comments
1.
Cool hack.
You can also do this:
class ActiveRecord::Base
def self.random
first(:order => 'rand()')
end
end
It's simpler and more concise, but depends on the database having a rand() function defined. (Works w/ MySQL; dunno about others.)
2.
@Joe,
Truth be told I got this from Koz:
https://rails.lighthouseapp.com/projects/8994/tickets/1274-patch-add-support-for-order-random-in-queries
He claims doing rand() in the order by is slower.
3.
Interesting.
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.
Comments Disabled