Is there a DELETED table in Rails just as in SQL Server?

假装没事ソ 提交于 2019-12-11 19:53:25

问题


I need to be able to do the same as demonstrated below in my rails app. As you can see, in SQL server there is a table called DELETED that stores those rows that were just deleted. source: How to create a before delete trigger in SQL Server?

CREATE TRIGGER TRG_AUD_DEL
ON yourTable
FOR DELETE
AS
     INSERT INTO my_audit_table  (col1, col2, ...)
     SELECT col1, col2...
     FROM DELETED 

Applying this logic to rails, is there such a table/location to call from to get those rows just as they are deleted in rails? I am aware of the callback before/after_destroy but how can you access that information that is being destroyed?


回答1:


Relying on database-specific behavior is not what ActiveRecord is about. It solely uses an RDBMS as a form of persistent storage. Data processing, such as this, is delegated to the app code.

ActiveRecord principles state that each row in the database is an instance of a model class in your app. Therefore, a callback is called on an instance of a model to be destroyed shortly.

Before a model is destroyed (before_destroy) your data should be accessible through class fields inside that callback. So you should be able to place this callback into one of your models you wish to keep track of:

def log_to_history
  DeletedStuff.create(
      title: "Something number #{id}",
      deleted_at: Time.now,
      content: self.to_yaml
    )
end

before_delete :log_to_history

It is a somewhat weird example that allows to store just about any deleted item (even different models' instances) in the same table, attributes are serialized with YAML. But I did my best to expose data structure, so it can be easily altered to suit your needs.

This example would require a DeletedStuff model with fields

  • title: string
  • deleted_at:time
  • content:text


来源:https://stackoverflow.com/questions/26081219/is-there-a-deleted-table-in-rails-just-as-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!