Rails选择随机记录 [英] Rails select random record

查看:53
本文介绍了Rails选择随机记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我只是在错误的地方还是在什么地方找东西,但是活动记录是否具有检索随机对象的方法?

I don't know if I'm just looking in the wrong places here or what, but does active record have a method for retrieving a random object?

有什么感觉吗?

@user = User.random

或者...好吧,因为这种方法不存在,所以有一些惊人的"Rails Way"来做到这一点,我似乎总是很冗长.我也在使用mysql.

Or... well since that method doesn't exist is there some amazing "Rails Way" of doing this, I always seem to be to verbose. I'm using mysql as well.

推荐答案

在Rails 4中,我将扩展ActiveRecord::Relation:

In Rails 4 I would extend ActiveRecord::Relation:

class ActiveRecord::Relation
  def random
    offset(rand(count))
  end
end

通过这种方式,您可以使用范围:

This way you can use scopes:

SomeModel.all.random.first # Return one random record
SomeModel.some_scope.another_scope.random.first

这篇关于Rails选择随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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