3

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

Abhaya
  • 2,086
  • 16
  • 21
Sadiksha Gautam
  • 5,032
  • 6
  • 40
  • 71

2 Answers2

1

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.

Ekampp
  • 755
  • 1
  • 6
  • 9
0

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
Steve
  • 15,606
  • 3
  • 44
  • 39
  • I did that also but this solution seems like a bit hack to me. I was thinking of whether paranoia would include something like this. Also, posts.delete_all will do hard delete, I would have to loop through posts and delete them individually. – Sadiksha Gautam Aug 17 '11 at 03:52
  • 1
    I agree its not all that elegant. It is a bit strange that callbacks get invoked but cascade rules don't. There is a related open issue at https://github.com/mongoid/mongoid/issues/857 so it may change in the future. There is a different solution suggested there - before_destroy :cascade! which might be a little less hacky. – Steve Aug 17 '11 at 07:53
  • I tried cascade also but it is only destroying post but what if post references_many :comments? in that case it is not deleting comments. – Sadiksha Gautam Aug 24 '11 at 08:10