查找一定数量的随机记录的“路轨4种方式"是什么? [英] What's the 'Rails 4 Way' of finding some number of random records?

查看:82
本文介绍了查找一定数量的随机记录的“路轨4种方式"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

User.find(:all, :order => "RANDOM()", :limit => 10)是我在Rails 3中做到的方式.

User.find(:all, :order => "RANDOM()", :limit => 10) was the way I did it in Rails 3.

User.all(:order => "RANDOM()", :limit => 10)是我认为Rails 4会这样做的方式,但这仍然给我一个过时警告:

User.all(:order => "RANDOM()", :limit => 10) is how I thought Rails 4 would do it, but this is still giving me a Deprecation warning:

DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`).

推荐答案

您将要改用orderlimit方法.您可以摆脱all.

You'll want to use the order and limit methods instead. You can get rid of the all.

对于PostgreSQL和SQLite:

For PostgreSQL and SQLite:

User.order("RANDOM()").limit(10)

或者对于MySQL:

User.order("RAND()").limit(10)

这篇关于查找一定数量的随机记录的“路轨4种方式"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆