两者有什么区别

@model.destroy和@model.delete

例如:

Model.find_by(col: "foo").destroy_all
//and
Model.find_by(col: "foo").delete_all

我用哪个真的重要吗?


当前回答

是的,这两种方法之间有一个主要的区别 如果您希望在不调用模型回调的情况下快速删除记录,请使用delete_all

如果你关心你的模型回调,那么使用destroy_all

来自官方文件

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.

其他回答

例子:

Class User
  has_many :contents, dependent: :destroy
end

user = User.last
user.delete -> only user
user.destroy -> delete user , and contents of user

delete将从db中删除当前记录(没有回调)

destroy将删除当前记录和相关记录(有回调)

delete_all和destroy_all也是如此

是的,这两种方法之间有一个主要的区别 如果您希望在不调用模型回调的情况下快速删除记录,请使用delete_all

如果你关心你的模型回调,那么使用destroy_all

来自官方文件

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.

基本上,“delete”直接向数据库发送查询以删除记录。在这种情况下,Rails不知道它正在删除的记录中有什么属性,也不知道是否有任何回调(比如before_destroy)。

“destroy”方法获取传递的id,使用“find”方法从数据库中获取模型,然后对其调用destroy。这意味着回调被触发。

如果你不想触发回调或者你想要更好的性能,你会想要使用“delete”。否则(大多数时候)你会想要使用“destroy”。

Delete只会从db中删除当前对象记录,而不会从db中删除其关联的子记录。

Destroy将从db中删除当前对象记录,并从db中删除其关联的子记录。

它们的使用真的很重要:

如果你的多个父对象共享公共的子对象,那么在特定的父对象上调用destroy将删除在其他多个父对象中共享的子对象。

当你在一个ActiveRecord对象上调用destroy或destroy_all时,ActiveRecord ' destroy '过程被启动,它会分析你要删除的类,它会确定它应该为依赖项做什么,运行验证等。

当你在一个对象上调用delete或delete_all时,ActiveRecord仅仅尝试对数据库运行delete FROM表名WHERE条件查询,不执行其他ActiveRecord级别的任务。