Mongoid:before_destroy和Paranoia

时间:2011-09-26 15:40:48

标签: ruby-on-rails ruby mongodb mongoid

Mongoid中是否有一些软删除回调?因为before_destory不会被触发。

现在我认为我可以使用before_update,但它看起来并不是我想要的解决方案,也不会被触发

class Message
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paranoia
  before_update :some_action

private

  def some_action
    if self.deleted_at_changed?
      ... # do my stuff
    end
  end
end

所以唯一的解决方案是从控制器中的destroy动作调用它吗?

3 个答案:

答案 0 :(得分:2)

Mongoid支持偏执文件。

你做的是包括偏执狂混合:

class Person
  include Mongoid::Document
  include Mongoid::Paranoia
end

然后观察以下新功能:

person.delete # Sets the deleted_at field to the current time.
person.delete! # Permanently deletes the document.
person.destroy! # Permanently delete the document with callbacks.
person.restore # Brings the "deleted" document back to life.

您可以在mogoid网站here上的文档的额外部分找到此信息。

答案 1 :(得分:2)

我做的是:

def delete_with_callbacks
  run_callbacks(:destroy) { delete_without_callbacks }
end
alias_method_chain :delete, :callbacks

答案 2 :(得分:1)

正如泰勒所说,你可以使用Mongoid::Paranoia。这将为您提供另一个选项::

message.remove

要查看是否已将其删除,您可以使用message.destroyed?

同样Message.deleted会从类消息中获取所有Soft Deleted(已删除)记录。

访问他们美丽的documentation以及此one