user938363
user938363

Reputation: 10360

Are there destroy_all!/delete_all! in Rails?

We are looking for a command to delete multiple records within Rails transaction. To make it trigger within transaction, we used destroy_all! and delete_all! and received method not defined error. What's the right delete command (or right way) for multiple records which triggers in Rails transaction?

Upvotes: 11

Views: 12223

Answers (4)

There are no methods called delete_all! or destroy_all! but look at the destroy_allsource code:

def destroy_all(conditions = nil)
    find(:all, :conditions => conditions).each { |object| object.destroy }
end

It calls method destroy and so I do not see any exceptions raise here. You can use this.

records.each &:destroy!

Upvotes: 1

Karl Lu
Karl Lu

Reputation: 71

The source code of destroy_all is:

def destroy_all(conditions = nil)
 find(:all, :conditions => conditions).each { |object| object.destroy }
end 

and object.destroy will only return false not raise errors to trigger transaction when deletion fails.

So, May be we need use it like:

ActiveRecord::Base.transaction do 
  records.each(&:destroy!) 
end

Right?

Upvotes: 2

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

No delete_all! or destroy_all! in Rails, but Rails has delete_all and destroy_all methods. Diference between these two methods are: delete_all only deletes the matching records with the given condition but doesn't delete the dependant/associated records where destroy_all deletes all the matching records along with their dependant/associated records. So, choose wisely between delete_all and destroy_all according to your need.

Upvotes: 1

Hoa
Hoa

Reputation: 3207

No, there are no methods called delete_all! or destroy_all!. See the documentation.

Use delete_all or destroy_all instead. These methods will raise ActiveRecord errors if deletion fails. It means your transaction will be rolled back in case of errors as you expected.

Upvotes: 18

Related Questions