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

查看:19
本文介绍了查找一些随机记录的“Rails 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:

Or for MySQL:

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

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

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