在ActiveRecord的随机记录ActiveRecord

2023-09-08 15:40:14 作者:你的她貌美如狗

我需要通过ActiveRecord的得到一个随机记录从表中。我已经按照从了Jamis巴克例如,从2006年。

I'm in need of getting a random record from a table via ActiveRecord. I've followed the example from Jamis Buck from 2006.

不过,我也遇到过另一种方式,通过谷歌搜索(由于新用户的限制不能以链接属性):

However, I've also come across another way via a Google search (can't attribute with a link due to new user restrictions):

 rand_id = rand(Model.count)
 rand_record = Model.first(:conditions => [ "id >= ?", rand_id])

我很好奇其他人如何在这里已经做了,或者有人知道什么样的方式会更有效。

I'm curious how others on here have done it or if anyone knows what way would be more efficient.

推荐答案

我还没有找到一种理想的方式做到这一点没有至少两个查询。

I haven't found an ideal way to do this without at least two queries.

下面使用一个随机生成的数字(上涨到目前的记录数)为的偏移的。

The following uses a randomly generated number (up to the current record count) as an offset.

offset = rand(Model.count)

# Rails 4
rand_record = Model.offset(offset).first

# Rails 3
rand_record = Model.first(:offset => offset)

说实话,我一直在使用ORDER BY RAND()或随机()(取决于数据库)。这不是一个性能问题,如果你没有一个性能问题。

To be honest, I've just been using ORDER BY RAND() or RANDOM() (depending on the database). It's not a performance issue if you don't have a performance issue.