2

我是 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自动处理吗?如果没有,我该如何编写删除/销毁回调来实现这一点?

4

0 回答 0