Select a random table row with ActiveRecord

Use this scope:

class Stick
  named_scope :shuffled, lambda {
    last_record = last
    { :conditions => [ 'id >= ?', rand(last_record.id) ] } if last_record
  }
end

You can now pick a random stick by saying

Stick.shuffled.first

Or, if you prefer something smaller:

class Stick
  named_scope :shuffled, :order => 'RAND()'
end

Note however that you should never order by RAND() on tables that may become large some day, as this performs horribly and can kill your database server.

Henning Koch Over 13 years ago