ActiveRecord 中的随机记录 [英] Random record in ActiveRecord
问题描述
我需要通过 ActiveRecord 从表中获取随机记录.我遵循了 2006 年的 Jamis Buck一>.
I'm in need of getting a random record from a table via ActiveRecord. I've followed the example from Jamis Buck from 2006.
但是,我还通过 Google 搜索找到了另一种方式(由于新用户限制,无法使用链接进行归因):
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() 或 RANDOM()(取决于数据库).如果您没有性能问题,那就不是性能问题.
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.
这篇关于ActiveRecord 中的随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!