两者有什么区别
@model.destroy和@model.delete
例如:
Model.find_by(col: "foo").destroy_all
//and
Model.find_by(col: "foo").delete_all
我用哪个真的重要吗?
两者有什么区别
@model.destroy和@model.delete
例如:
Model.find_by(col: "foo").destroy_all
//and
Model.find_by(col: "foo").delete_all
我用哪个真的重要吗?
当前回答
当你在一个ActiveRecord对象上调用destroy或destroy_all时,ActiveRecord ' destroy '过程被启动,它会分析你要删除的类,它会确定它应该为依赖项做什么,运行验证等。
当你在一个对象上调用delete或delete_all时,ActiveRecord仅仅尝试对数据库运行delete FROM表名WHERE条件查询,不执行其他ActiveRecord级别的任务。
其他回答
基本上destroy会运行模型上的任何回调,而delete则不会。
来自Rails API:
ActiveRecord::Persistence.delete 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. The row is simply removed with an SQL DELETE statement on the record's primary key, and no callbacks are executed. 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). 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.
是的,这两种方法之间有一个主要的区别 如果您希望在不调用模型回调的情况下快速删除记录,请使用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只会从db中删除当前对象记录,而不会从db中删除其关联的子记录。
Destroy将从db中删除当前对象记录,并从db中删除其关联的子记录。
它们的使用真的很重要:
如果你的多个父对象共享公共的子对象,那么在特定的父对象上调用destroy将删除在其他多个父对象中共享的子对象。
当你在一个ActiveRecord对象上调用destroy或destroy_all时,ActiveRecord ' destroy '过程被启动,它会分析你要删除的类,它会确定它应该为依赖项做什么,运行验证等。
当你在一个对象上调用delete或delete_all时,ActiveRecord仅仅尝试对数据库运行delete FROM表名WHERE条件查询,不执行其他ActiveRecord级别的任务。
例子:
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也是如此