MongoMapper + Cascade删除?

时间:2011-08-08 06:04:42

标签: ruby-on-rails ruby mongomapper

带有Identity Map的MongoMapper是否支持级联删除?它似乎并不是真的,但我可能会遗漏文档中的某些内容。请考虑以下事项:

class User
  include MongoMapper::Document
  many :comments
end

class Comment
  include MongoMapper::Document
  belongs_to :user
end

user = User.create!
user.comments.create!
user.destroy

我希望user.destroy也可以级联到评论 - 或者至少能够配置它来执行此操作。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

为此,您需要使用嵌入式文档:

class User
  include MongoMapper::Document
  many :comments
end

class Comment
  include MongoMapper::EmbeddedDocument
  belongs_to :user
end

user = User.create!
user.comments.create!
user.destroy

这也有一些缺点......

答案 1 :(得分:0)

您可以在User模型中构建自己的模型:

before_destroy :destroy_comments
...
def destroy_comments
  comments.each {|c| c.destroy}
end

可能是抽象/通用的......