依赖破坏不起作用

编程入门 行业动态 更新时间:2024-10-23 10:23:01
本文介绍了依赖破坏不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用依赖::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_many,destroy 和destroy_all 将始终调用记录的destroy 方法删除以便运行回调.但是 delete 和 delete_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).

更多推荐

依赖破坏不起作用

本文发布于:2023-10-16 05:47:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!