依赖破坏不起作用 [英] dependent destroy not working

查看:41
本文介绍了依赖破坏不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用依赖::destroy 没有成功.

I'm trying to use dependent: :destroy without success.

让我们举一个简单的例子.我使用以下内容创建了一个简单的应用程序:

Lets put a simple example. I create a simple application with the following:

rails g model parent
rails g model child parent:references

将以下几行添加到 parent.rb

Add following lines to parent.rb

has_many :children, dependent: :destroy

我在 rails 控制台 (rails c) 中做了以下测试

I do the following test in rails console (rails c)

p = Parent.create!
c = Child.create!
c.parent = p
c.save
#check association
Child.first == Child.first.parent.children.first
p.delete
#This should return 0
Child.count == 0

Child.count 返回 1.

And Child.count returns 1.

我缺少什么?

谢谢

推荐答案

4.2.2.4 :dependent

如果您将 :dependent 选项设置为:

If you set the :dependent option to:

  • :destroy,当对象被销毁时,会在其关联的对象上调用#destroy.
  • :delete,当对象被销毁时,其所有关联的对象将直接从数据库中删除而无需调用它们的#destroy 方法.
  • :destroy, when the object is destroyed, #destroy will be called on its associated objects.
  • :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their #destroy method.

根据您的设置,您必须执行p.destroy.

As per your settings, you have to do p.destroy.

:dependent 选项可以有不同的值来指定删除是如何完成的.有关更多信息,请参阅有关不同特定关联类型的此选项的文档.当没有给出选项时,行为是在销毁记录时不对关联的记录做任何事情.

The :dependent option can have different values which specify how the deletion is done. For more information, see the documentation for this option on the different specific association types. When no option is given, the behaviour is to do nothing with the associated records when destroying a record.

对于has_manydestroydestroy_all 将始终调用记录的destroy 方法删除以便运行回调.但是 deletedelete_all 要么根据 :dependent 选项指定的 strategy 进行删除,要么没有给出 :dependent 选项,那么它将遵循默认策略.默认策略是:nullify(将外键设置为nil),除了has_many :through,默认策略是delete_all(删除连接记录,不运行它们的回调).

For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify (set the foreign keys to nil), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

这篇关于依赖破坏不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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