I would like to log some information when the user deletes things on my system.
The premise is simple, if I delete it I'll record it in the log_delete table.
I know it's possible to do this using before_destroy, however, I would like the implementation to be transparent, and not need to add before_destroy to every model.
That way the developer doesn't have to worry about putting this in if he creates a new model.
Is there any way to use something like before_destroy for all models?
CodePudding user response:
You should have an ApplicationRecord like this:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
# Maybe some other stuff...
end
as a base class for all your ActiveRecord models.
You could put a before_destroy there and then the callback can pull whatever information out of self and self.class that it needs to log.
ApplicationRecord has been standard practice since, AFAIK, Rails 5 so it should be in place and if it isn't, you really should add one.
Alternatively you could use a database trigger and let the database take care of it. I tend to think a trigger is where this sort of thing belongs and has the benefit of being a lot harder to get around (either intentionally or accidentally). On the downside, this requires a small amount of database-specific coding but that's nearly impossible to avoid in any non-trivial application.
