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?
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:
random()
, MySQL uses rand()
, 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 applying ORDER BY random()
to..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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With