Difference between Destroy and Delete

前端 未结 6 996
慢半拍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:42

    Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy).

    The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.

    You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".

提交回复
热议问题