问题描述
和
@model.destroy
和 @model.delete
例如:
Model.find_by(col: "foo").destroy_all
//and
Model.find_by(col: "foo").delete_all
我使用一种还是另一种真的很重要吗?
Does it really matter if I use the one or the other?
推荐答案
基本上 destroy
会在模型上运行任何回调,而 delete
不会.
Basically destroy
runs any callbacks on the model while delete
doesn't.
来自 Rails API:
删除数据库中的记录并冻结此实例以反映不应进行任何更改(因为它们无法持久化).返回冻结的实例.
使用记录主键上的 SQL DELETE 语句简单地删除该行,并且不执行任何回调.
The row is simply removed with an SQL DELETE statement on the record's primary key, and no callbacks are executed.
要强制执行对象的 before_destroy 和 after_destroy 回调或任何 :dependent 关联选项,请使用 #destroy.
To enforce the object's before_destroy and after_destroy callbacks or any :dependent association options, use #destroy.
ActiveRecord::Persistence.destroy
删除数据库中的记录并冻结此实例以反映不应进行任何更改(因为它们无法持久化).
有一系列与销毁相关的回调.如果 before_destroy 回调返回 false,则操作被取消,destroy 返回 false.有关详细信息,请参阅 ActiveRecord::Callbacks.
There's a series of callbacks associated with destroy. If the before_destroy callback return false the action is cancelled and destroy returns false. See ActiveRecord::Callbacks for further details.
这篇关于销毁和删除的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!