Skip to content

Instantly share code, notes, and snippets.

@kaspth
Last active January 19, 2024 19:40
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaspth/11516d3b47da6b8a5f7c3dba7a493cf1 to your computer and use it in GitHub Desktop.
Save kaspth/11516d3b47da6b8a5f7c3dba7a493cf1 to your computer and use it in GitHub Desktop.
A Rails modeling implementation of https://brandur.org/soft-deletion
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