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:
- PostgreSQL and SQLite use
random()
, MySQL usesrand()
, I'm not sure about other databases. 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 applyingORDER BY random()
to.- A
.limit
will be applied after the ORDER BY sox.limit(n).order('random()')
will apply the ORDER BY to all ofx
and then applylimit(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