在 mongoid 中使用 has_many_and_belongs_to 删除子关系
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论