2

I have the following rudimentary piece of code in my model to return a random event:

def self.random
  Event.first(:offset => rand(Event.count))
end

I would like to modify the function so it returns N number of events.

I'm aware that first can take a number as a parameter, i.e. Event.first(2), but how to combine it with random offset?

I.e. something like this

def self.random(n = 1)
  Event.first(n) # and offset??!!
end

Any help would be appreciated!

alexs333
  • 12,143
  • 11
  • 51
  • 89
  • See also [Random record in ActiveRecord](http://stackoverflow.com/questions/2752231/random-record-in-activerecord). In particular, I prefer using the [randumb](https://github.com/spilliton/randumb) gem. – Alistair A. Israel Apr 04 '13 at 04:50

2 Answers2

2

This should work for returning n random records:

def self.random(n = 1)
  Event.order("RANDOM()").limit(n)
end

The limit method is actually called by first when you give it an Integer as the first argument, so you could also use .first(n) instead of .limit(n) if you prefer.

You may need to substitute RAND() instead of RANDOM() depending on your database system, consult the documentation for the exact method.

Stuart M
  • 11,458
  • 6
  • 45
  • 59
2

While Stuarts method works perfectly by itself, it cannot be chained with many other ActiveRecord scopes. I found the other method (using offset) that works with chaining:

  def self.random(number = 1)
    Event.offset(rand(Event.count - number+1)).first(number)
  end
alexs333
  • 12,143
  • 11
  • 51
  • 89