nobody
nobody

Reputation: 8263

ActiveRecord destroy_all

In Rails 4.1, does the ActiveRecord destroy_all wrap the entire function in a transaction? For example, if I have a bunch of records that I do a destroy_all operation on and they run some callbacks on those individual objects and one of those fails does the entire operation rollback at that point?

Upvotes: 6

Views: 3310

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

Looking at the destroy_all documentation, it does not seem to be done within a transaction. Here is the source code:

  # activerecord/lib/active_record/base.rb, line 879
  def destroy_all(conditions = nil)
    find(:all, :conditions => conditions).each { |object| object.destroy }
  end

It finds all the records and calls .destroy on each of them. From the doc:

Destroys the records matching conditions by instantiating each record and calling its destroy method.

But, if you want to make it happen in one transaction, you can wrap your destroy_all code in a transaction to make sure it's happening in one single transaction:

ActiveRecord::Base.transaction do
  YourModel.destroy_all(:conditions => conditions)
end

Upvotes: 2

joshua.paling
joshua.paling

Reputation: 13952

It doesn't look like it:

# File activerecord/lib/active_record/relation.rb, line 386
def destroy_all(conditions = nil)
  if conditions
    where(conditions).destroy_all
  else
    to_a.each {|object| object.destroy }.tap { reset }
  end
end

(from http://apidock.com/rails/v4.1.8/ActiveRecord/Relation/destroy_all)

Of course, you could wrap it in a transaction of your own.

Upvotes: 8

Related Questions