0

I am trying to delete thousands of records from my db using delayed_jobs. Right now it deletes the queries but there is an infinite loop I see in my logs where it keeps querying for records in the db to delete them even if there are none.

my code below self.get_all_calls is where I loop through and destroy 5000 records at once and I want to sleep for 2 seconds and then do it again another 5000 until all have been deleted.

Is there a way to just do Calls.where(account_name: y).limit(5000).destroy_all and have that do 5000 records at once and then sleep and do it again and again until it is done instead of doing the way I am doing it below or a way to fix my code below to stop the infinite loop?

def destroy_calls
  y = self.name
  counts = Call.where(account_name: self.name)
  count = counts.count
  User.delay(run_at: 2.minutes.from_now).get_all_calls(y, count)
end
 
def self.get_all_calls(y,count)
  until count == 0
    Call.where(account_name: y).limit(5000).each do |x|
    x.destroy
    count-1
  end
    sleep(2)
  end
end 
kbob
  • 45
  • 5
  • 3
    Check `in_batches` method: https://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-in_batches For the infinite loop, reason is `count-1`. it should be `count -= 1` – Emu Oct 01 '20 at 03:26
  • Does this answer your question? [Using ActiveRecord find\_in\_batches method for deleting large data](https://stackoverflow.com/questions/33022337/using-activerecord-find-in-batches-method-for-deleting-large-data) – Hass Oct 01 '20 at 04:29

0 Answers0