Difference between Destroy and Delete

前端 未结 6 993
慢半拍i
慢半拍i 2020-11-27 11:00

What is the difference between

@model.destroy and @model.delete

For example:

Model.find_by(col: \"foo\").destroy_         


        
6条回答
  •  眼角桃花
    2020-11-27 11:52

    Yes there is a major difference between the two methods Use delete_all if you want records to be deleted quickly without model callbacks being called

    If you care about your models callbacks then use destroy_all

    From the official docs

    http://apidock.com/rails/ActiveRecord/Base/destroy_all/class

    destroy_all(conditions = nil) public

    Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).

    Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.

提交回复
热议问题