Reputation: 10360
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
Reputation: 29
There are no methods called delete_all!
or destroy_all!
but look at the destroy_all
source 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
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
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
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