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

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.

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

a = store.items.all.shuffle