0

I was using the following method in my Rails 4 app to get random records in a model:

Model.order('RANDOM()').limit(5)

This broke after upgrading to Rails 4.0.2. It's always getting the most recent records. Any ideas why?

6thSigma
  • 248
  • 1
  • 7

2 Answers2

2

You either need to remove the default scope from your model or call it like this:

Model.unscoped.order('RANDOM()').limit(5)
Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
0

Simply use Model.all.sample(5)

Ishank Gupta
  • 1,575
  • 1
  • 14
  • 19
  • 1
    This may work okay for very small data sets, but the above will be very inefficient if Modal.all returns any significant number of rows as they will all be returned, objects instantiated, and only then will Array#sample randomly pick 5 of them. – Philip Hallstrom Feb 03 '14 at 18:41
  • 2
    [For more information of what Philip is referring to](http://stackoverflow.com/a/12038506/877472) – Paul Richter Feb 03 '14 at 18:42
  • Yup...got what you are saying. Thanks. – Ishank Gupta Feb 03 '14 at 18:46