Ruby on Rails Active Record RANDOM() always the same within a loop

僤鯓⒐⒋嵵緔 提交于 2019-12-14 01:26:18

问题


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

Output:

ID: 82784
ID: 82784
ID: 82784
ID: 82784
ID: 82784

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?


回答1:


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.



来源:https://stackoverflow.com/questions/34583074/ruby-on-rails-active-record-random-always-the-same-within-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!