在 mongoid 中使用 has_many_and_belongs_to 删除子关系

发布于 2024-12-12 19:08:27 字数 762 浏览 0 评论 0原文

我是 Rails 新手,正在尝试使用 Mongoid 找出关联。

我有一个图片模型,可以有多种颜色,一种颜色可以属于多张图片。查询应该双向工作(即图片 -> 颜色和颜色 -> 图片),所以我决定使用 has_many_and_belongs_to 关联。

Class Picture
  include Mongoid::Document
  has_many_and_belongs_to :colors

标签模型

Class Color
  include Mongoid::Document
  has_many_and_belongs_to :pictures

现在,我想对 进行设置,以便当删除与某种颜色相关的所有图片时,该颜色也会被删除。我尝试依赖于销毁和删除,但它们似乎都不起作用。

p1 = Picture.new
p2 = Picture.new
c = Color.new
p1.colors.push(c)
p2.colors.push(c)

p1.delete # <-- c is still associated with p2. This should not delete c
p2.delete # <-- c has no more associations. It should automatically be deleted now

Rails 可以自动处理这个问题吗?如果没有,我该如何编写删除/销毁回调来实现这一点?

I'm new to rails and trying to figure out associations using Mongoid.

I have a Picture model that can have many colors, and one color can belong to many pictures. Queries should work in both directions (ie Picture -> Colors and Color -> Pictures), so I decided to go with has_many_and_belongs_to association.

Class Picture
  include Mongoid::Document
  has_many_and_belongs_to :colors

Now the Tag Model

Class Color
  include Mongoid::Document
  has_many_and_belongs_to :pictures

I'd like to set it up so that when all the pictures associated to a color are deleted, the color is also deleted. I tried dependent with destroy and delete but none of them seem to work.

p1 = Picture.new
p2 = Picture.new
c = Color.new
p1.colors.push(c)
p2.colors.push(c)

p1.delete # <-- c is still associated with p2. This should not delete c
p2.delete # <-- c has no more associations. It should automatically be deleted now

Can this be automatically handled by rails? If not, how can I write delete/destroy callbacks to make this happen?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文