软删除 mongoid 文档以及关联文档

发布于 2024-11-29 19:19:37 字数 433 浏览 2 评论 0原文

我有 2 个模型、用户和帖子

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  references_many :posts, :autosave => true, :dependent => :destroy
end

class Post
  include Mongoid::Document
  referenced_in :user
end

现在当我软删除用户时,我也想软删除帖子。我有什么办法可以做到这一点吗?

对于软删除文档,我使用 Mongoid::Paranoia

I have 2 models, user and posts

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  references_many :posts, :autosave => true, :dependent => :destroy
end

class Post
  include Mongoid::Document
  referenced_in :user
end

Now when I soft delete user, I also want to soft delete posts. Is there any way I can do this?

For soft deleting a document I am using Mongoid::Paranoia

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独难免 2024-12-06 19:19:37

为什么要删除用户的帖子?如果我正在关注某个线程(我假设这些帖子是线程式的),并且某个在线程中写了一些帖子的用户删除了他的个人资料,我不希望他的帖子被删除。这会破坏后线程的流程。

我知道这并不能回答您的问题,但这可能是考虑您是否确实需要删除帖子的理由。

Why would you want to delete the users posts? If I was following some thread (I assume that the posts are threaded), and some user, who wrote some posts in the threads, deleted his profile, I wouldn't like his posts to be removed. This would break the flow of the post-thread.

I'm aware that this doesn't answer your question, but it might be grounds for considering if you really need to delete the posts.

不羁少年 2024-12-06 19:19:37

before_destroy 回调可以满足您的需要吗?例如

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  references_many :posts, :autosave => true, :dependent => :destroy
  before_destroy :delete_posts

  def delete_posts
    posts.delete_all
  end
end

class Post
  include Mongoid::Document
  include Mongoid::Paranoia
  referenced_in :user
end

Would a before_destroy callback do what you need? e.g.

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  references_many :posts, :autosave => true, :dependent => :destroy
  before_destroy :delete_posts

  def delete_posts
    posts.delete_all
  end
end

class Post
  include Mongoid::Document
  include Mongoid::Paranoia
  referenced_in :user
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文