DEPRECATION WARNING: Dangerous query method: Random Record in ActiveRecord >= 5.2

前端 未结 3 1799
长发绾君心
长发绾君心 2020-11-29 12:13

So far, the \"common\" way to get a random record from the Database has been:

# Postgress
Model.order(\"RANDOM()\").first 

# MySQL
Model.order(\"RAND()\").f         


        
3条回答
  •  我在风中等你
    2020-11-29 12:46

    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.

提交回复
热议问题