If you want to continue using order by random()
then just declare it safe by wrapping it in Arel.sql
like the deprecation warning suggests:
Model.order(Arel.sql('random()')).first # PostgreSQL
Model.order(Arel.sql('rand()')).first # MySQL
There are lots of ways of selecting a random row and they all have advantages and disadvantages but there are times when you absolutely must use a snippet of SQL in an order by
(such as when you need the order to match a Ruby array and have to get a big case when ... end
expression down to the database) so using Arel.sql
to get around this “attributes only” restriction is a tool we all need to know about.
Edited: The sample code is missing a closing parentheses.