Select a random table row with ActiveRecord

Updated . Posted . Visible to the public.

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
Last edit
Keywords
sample, database, record
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-11-04 16:24)