问题
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