Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Ben Nelson Avatar asked Nov 04 '15 23:11

Ben Nelson


2 Answers

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.

like image 80
joshua.paling Avatar answered Oct 20 '22 00:10

joshua.paling


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
like image 35
K M Rakibul Islam Avatar answered Oct 19 '22 22:10

K M Rakibul Islam