Are there destroy_all!/delete_all! in Rails?
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.
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.
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?