I'm in need of getting a random record from a table via ActiveRecord. I've followed the example from Jamis Buck from 2006.
However, I've also come across another way via a Google search (can't attribute with a link due to new user restrictions):
rand_id = rand(Model.count)
rand_record = Model.first(:conditions => ["id >= ?", rand_id])
I'm curious how others on here have done it or if anyone knows what way would be more efficient.
You can use the
Array
methodsample
, the methodsample
returns a random object from an array, in order to use it you just need to exec in a simpleActiveRecord
query that return a collection, for example:will return something like this:
For MySQL database try: Model.order("RAND()").first
Rails 4.2 and Oracle:
For oracle you can set a scope on your Model like so:
or
And then for a sample call it like this:
or
of course you could also place an order without a scope like so:
I made a rails 3 gem to handle this:
https://github.com/spilliton/randumb
It allows you do do stuff like this:
What about to do:
For me is much clear
It doesn't have to be that hard.
pluck
returns an array of all the id's in the table. Thesample
method on the array, returns a random id from the array.This should perform well, with equal probability of selection and support for tables with deleted rows. You can even mix it with constraints.
And thereby pick a random user who likes fridays rather than just any user.