has_one 关联中 :dependent 的 :destroy 和 :delete 之间的区别

use*_*363 1 ruby-on-rails

在 Rails 文档Active Record Associations 中:dependentfor的前两个值has_one是:

4.2.2.4 :dependent

Controls what happens to the associated object when its owner is destroyed:

    :destroy causes the associated object to also be destroyed
    :delete causes the associated object to be deleted directly from the database (so callbacks will not execute)
Run Code Online (Sandbox Code Playgroud)

我的理解:destroy是,例如,一个customer has_one address. 用:dependent => :destroy, 如果customer被删除,那么address在从数据库customer中删除后会自动从数据库中删除,我们通常使用:destroy. 有什么用:delete

Jan*_*dek 5

两者几乎一样,我说几乎,因为:

从属: :destroy - 在关联对象中调用回调(before_destroy、after_destroy),然后你就可以中断事务(在回调中引发错误)。

从属: :delete - 不调用回调(它通过 SQL 直接从数据库中删除对象,如 DELETE FROM ... WHERE ...)