I'm been searching high and low to find a way to safely run delete_all within a model's method and not incur a web server timeout (say 30 seconds).
Let's say the scenario is as follows: I may have 50K Item records and 150k related ItemHistory records. Clearly using destroy_all
(which loads an instance of each record and sends individual deletes) isn't optimal. How would you approach this problem? I also have delayed_job and tried using the .delay
method but don't believe it's a good fit for this issue. So, I started looking at Threads, but I would like to employ them safely.
Scenario #1 destroying hundreds of thousands of expired records
Thread.new do
Item.expired.find_each do |item|
item.destroy_all # this will also destroy ItemHistory records
end
ActiveRecord::Base.connection.close
end
Similarly to the previous question, what are there pitfalls of using a transaction within a Thread (I imagine this is supported)?
Scenario #2 - using transaction within a Thread
Thread.new do
ActiveRecord::Base.transaction do
User.import(account_id)
Item.import(account_id)
end
ActiveRecord::Base.connection.close
end
Are there any gotchas I need to consider?