Ruby on Rails Active Record RANDOM()在循环内始终相同 [英] Ruby on Rails Active Record RANDOM() always the same within a loop
问题描述
为什么每次循环迭代都应获取随机记录时,为什么会重复输出相同的记录ID?
Why does this output the same record ID repeatedly, when it should be grabbing a random record each loop iteration?
count = 0
while count < 20
puts "ID: " + SomeModel.where(assoc_id: 10).order("RANDOM()").limit(1).first.id.to_s
count += 1
end
输出:
ID: 82784
ID: 82784
ID: 82784
ID: 82784
ID: 82784
我已经确保查询中有足够的记录(即多于1条).在控制台内,该行本身(在循环外部)每次都会返回一个新的ID,因此它与循环有关.我不明白什么?
I have already ensured there are sufficient records available with the query (ie more than 1). Within a console, the line by itself (outside of a loop) will return a new ID every time, so it has something to do with the loop. What am I not understanding?
推荐答案
我相信是由于 ActiveRecord缓存而发生的.您可以阅读此博客文章关于非常相似的内容解决您的问题及其解决方案.简而言之,他们(和您)可以使用 ActiveRecords未缓存的方法以免重复.
I believe that's happening because of ActiveRecord caching. You can read this blog post about something very similar to your problem and their solution. In short, they (and you) can make use of ActiveRecords uncached method to not see it repeating.
这篇关于Ruby on Rails Active Record RANDOM()在循环内始终相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!