开发者

Mongoid: before_destroy and Paranoia

开发者 https://www.devze.com 2023-04-07 10:22 出处:网络
Is there some callbacks for soft deleting in Mongoid? Because before_destory won\'t be triggered. Now I thought I can use before_update but it looks开发者_开发问答 not so clear solution as I want and

Is there some callbacks for soft deleting in Mongoid? Because before_destory won't be triggered.

Now I thought I can use before_update but it looks开发者_开发问答 not so clear solution as I want and it is not triggered as well

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

So the only solution is to call it from destroy action in controller?


What I did is:

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


Mongoid supports paranoid documents.

What you do is include the Paranoia mixin:

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

Then observe the following new features:

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.

You can find this information in the extra part of the documentation on the mogoid website here.


As Tyler mentioned, you can use Mongoid::Paranoia. This will give you another option ::

message.remove

To check to see if it has been deleted or not, you can use message.destroyed?.

Also Message.deleted would fetch you all the Soft Deleted (removed) records from class Message.

Visit their beautiful documentation along with this one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号