销毁和删除的区别 [英] Difference between Destroy and Delete

查看:40
本文介绍了销毁和删除的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@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:

删除数据库中的记录并冻结此实例以反映不应进行任何更改(因为它们无法持久化).返回冻结的实例.

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

使用记录主键上的 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

    删除数据库中的记录并冻结此实例以反映不应进行任何更改(因为它们无法持久化).

    Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted).

    有一系列与销毁相关的回调.如果 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.

  • 这篇关于销毁和删除的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆