Last active
January 19, 2024 19:40
-
-
Save kaspth/11516d3b47da6b8a5f7c3dba7a493cf1 to your computer and use it in GitHub Desktop.
A Rails modeling implementation of https://brandur.org/soft-deletion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create_table :stowaway_records do |t| | |
t.string :record_type, null: false | |
t.jsonb :record_attributes, null: false, default: {} | |
t.timestamps | |
t.index :record_type | |
end | |
class Stowaway::Record < ActiveRecord::Base | |
def self.preserve(record) | |
create! record_type: record.class, record_attributes: record.attributes | |
end | |
def record | |
record_type.constantize.then do | |
_1.new record_attributes.slice(*_1.attribute_names) | |
end | |
end | |
def recreate! | |
transaction do | |
record.save! | |
destroy! | |
end | |
end | |
end | |
class ApplicationRecord < ActiveRecord::Base | |
has_stowaway # Would do this: | |
def self.stowaway = Stowaway::Record.where(record_type: self) | |
before_destroy { Stowaway::Record.preserve(self) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment