user.rb模型
class User
include Mongoid::Document
include Mongoid::Paranoia
has_many :posts, dependent: :destroy, :autosave => true
end
post.rb模型
class Post
include Mongoid::Document
belongs_to :user
field :title
end
如果我在控制台中运行下一个命令:
irb(main):020:0> u = User.first
=> #object here
irb(main):021:0> u.delete
=> true
irb(main):022:0> u.posts
=> nil
如果我尝试调用用户帖子,我可以看到所有用户帖子 已被删除。如果使用 u.destroy
将用户从我的数据库中永久销毁,我希望仅删除所有用户帖子。
如果我使用 Mongoid::Paranoia
删除一个对象,我如何在我的数据库中保留所有相关对象 u.delete
for this object can be restore稍后使用 u.restore
谢谢!
最佳答案
您可以覆盖 remove
method在由 Mongoid::Paranoia
提供的 User
中,因此它省略了 cascade!
调用:
def remove(options = {})
# don't cascade the remove call
# cascade!
time = self.deleted_at = Time.now
paranoid_collection.find(atomic_selector).
update({ "$set" => { paranoid_field => time }})
@destroyed = true
IdentityMap.remove(self)
Threaded.clear_options!
true
end
alias :delete :remove
现在 u.delete
将完整保留所有关联的帖子,u.delete!
也将永久删除它们。
关于ruby-on-rails - Mongoid::Paranoia 删除关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637940/