Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize array element positions of an `ActiveRecord::Relation`?

I am running Ruby on Rails 3.2.2 and I would like to randomize array element positions of an ActiveRecord::Relation.

How can I do that?

like image 626
Backo Avatar asked Mar 14 '12 06:03

Backo


2 Answers

You could always add .order('random()') to the relation:

ar = Model.where(...).where(...).order('random()')

You could even add that as a scope:

class Model < ActiveRecord::Base
  scope :randomize, order('random()')
end

There are a few things to be aware of:

  1. PostgreSQL and SQLite use random(), MySQL uses rand(), I'm not sure about other databases.
  2. ORDER BY random() can be quite expensive in the database so you don't want to use this unless your WHERE clauses (i.e. .where calls) will limit the size of the result set that you will be applying ORDER BY random() to.
  3. A .limit will be applied after the ORDER BY so x.limit(n).order('random()') will apply the ORDER BY to all of x and then apply limit(n) after the sorting. This is where the warning in (2) comes from.
like image 180
mu is too short Avatar answered Nov 15 '22 19:11

mu is too short


Given that Store.items is a has_many relation, you can do

a = store.items.all.shuffle
like image 35
Baldrick Avatar answered Nov 15 '22 17:11

Baldrick