简体   繁体   中英

Keeping track of destroyed objects

I searched stack-overflow for similar approaches and didn't find anything so here goes my question:

I need to be able to keep track if a destroy has happened on a object and the time it happened. I also don't really need the whole object just the id it had.

Is there a gem that does this or do it need to handle this in my database?

The observer pattern should be used for that.

You need to create a model which observes your model:

class AuditObserver < ActiveRecord::Observer
  observe :account

  def after_destroy(account)
    p "#{account.id} destroyed"
  end
end

Here the AuditObserver observes the Account model and prints out the message if an account has been destroyed.

Keep in mind, that you need to add your observers to your configuration ( config/appplication.rb ) as:

config.active_record.observers = :audit_observer

Update

If you want to have the destroyed objects for a certain period, you can use the rails3_acts_as_paranoid gem.

Then you can fetch the deleted accounts as:

Account.deleted_after_time(time)

Or you can create a new model ( Audit ) and you can insert the destroyed ids with the timestamp into that table.

如果您不介意保留记录,可以使用偏执狂gem ,它会添加一个deleted_at时间戳并使用它来deleted_at模型范围,因此默认情况下会排除已删除的记录。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM