1

Im just a bit curious as to what would happen in this scenario

(My setup is a MongoDB, Ruby on Rails via MongoID)

Models.all.each do |model|
    model.destroy           #delete the record
    newmodel = model.new    #make a new record
    newmodel.someinfo = info  #fill it with some info
    newmodel.save   #save it
end

If we destroy the records while looping through and make a new one.
Would we loop through forever (because we're deleting the old one and adding a new one)

What I mean to ask is perhaps would we loop through the new records that we would have added (on the line that says #save it)

If not how would we code it to get that desired effect (loop through twice?) - Say I wanted an infinitely processing rake task?

Tarang
  • 75,157
  • 39
  • 215
  • 276

1 Answers1

1

If you have enough memory for the task you can use Models.all.entries.each instead of Models.all.each.

The way you are currently iterating through the record uses mongodb cursors, which can or can not(I am not sure) loop infinitely.

However, Models.all.entries will fetch the documents from db before iterating on them, so you can be sure that you will not be iterating on newly created documents. Beware, it will hog a lot of memory if you have a lot of bulky documents.

rubish
  • 10,887
  • 3
  • 43
  • 57