问题
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: stringdeleted_at:timecontent:text
来源:https://stackoverflow.com/questions/26081219/is-there-a-deleted-table-in-rails-just-as-in-sql-server