sundayAdefila sundayAdefila - 3 days ago 5
Ruby Question

Using ActiveRecord find_in_batches method for deleting large data

Okay, so I know that when dealing with very large data, we can use

find_in_batches
which, as I understand it, does the work of
Model.all.each
in a really fast way which is much more efficient

Now, I have a really large data I'm trying to delete, and I'm thinking of using this same
find_in_batches
to delete them in batches.

below is what I have (from within the rake task
database.rake
):

old_messages = TextMessage.where("created_at < ?", number.days.ago )

old_messages.find_in_batches do |batch|
batch.delete_all
end


When I run this however, I get the following error:

ArgumentError: wrong number of arguments (0 for 1..3)
/Users/Sunday/.rvm/gems/ruby-2.2.0/gems/httparty-0.13.5/lib/httparty.rb:66:in `logger'
/Users/Sunday/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.2/lib/active_record/relation/delegation.rb:94:in `public_send'
/Users/Sunday/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.2/lib/active_record/relation/delegation.rb:94:in `block in method_missing'
/Users/Sunday/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.2/lib/active_record/relation.rb:302:in `scoping'
/Users/Sunday/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.2/lib/active_record/relation/delegation.rb:94:in `method_missing'
/Users/Sunday/.rvm/gems/ruby-2.2.0/gems/activerecord-4.2.2/lib/active_record/relation/batches.rb:112:in `find_in_batches'
/Users/Sunday/workspace/resilience/lib/tasks/database.rake:18:in `block (2 levels) in <top (required)>'


where
database.rake
on line 18 is:
old_messages.find_in_batches do |batch|
.

So, is it possible to use
find_in_batches
for deleting like I'm trying to do? and what am I doing wrong, if the answer to that is yes. Thanks for all response.

Answer

Running

TextMessage.where("created_at < ?", number.days.ago ).delete_all 

will execute single query and will be effective enough. You do not need batches here.

Comments