有没有办法在ActiveRecord中多次获取随机记录?

时间:2019-01-20 16:36:44

标签: ruby-on-rails

我试图多次从表中获取几条随机记录。

我尝试了以下方法:

random = []
10.times {random.push(People.order("RAND()").limit(5))}

我希望从表中以随机顺序得到10个不同列表,其中包含5个随机人。但是,相反,我得到了10次相同的5个人名单。我在做什么错了?

编辑:

这也是我从日志中得到的内容

People Load (1.2ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5
CACHE People Load (0.0ms) SELECT  `peoples`.* FROM `peoples` ORDER BY RAND() LIMIT 5

Edit2:

已通过

修复
random = []
People.uncached do
  10.times {random.push(People.order("RAND()").limit(5))}
end

0 个答案:

没有答案