Module: ActiveRecord::Random

Defined in:
lib/activerecord_random.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#randomObject

ActiveRecord::Base.random returns a random instance of self.

This method does not use SQL RAND(). Instead, it performs a record count and then uses Ruby rand.

Example

Question.random #=> Random instance of random

ActiveRecord::Base.random is a safe method, thus when your model’s table is empty it will simply return nil.



15
16
17
18
19
20
21
# File 'lib/activerecord_random.rb', line 15

def random
  if minimum = self.minimum(:id)
    where("id >= ?", ::Random.new.rand(minimum..self.maximum(:id))).first
  else
    nil
  end
end