protected
def delete(*args)
raise ProtectedModelError.new
end
def destroy_all(*args)
raise ProtectedModelError.new
end
def destroy(*args)
raise ProtectedModelError.new
end
module ClassMethods
def delete_all(*args)
raise ProtectedModelError.new
end
end
end
end
class Query < ActiveRecord::Base
include ActiveRecord::ProtectedModel if Rails.env.production?
end
In what instance would people be calling destroy on your model without realising that it’s supposed to be protected? Who is this protecting the model from?
I’m not sure if this does the same but you could add readonly in
the default_scope, this way all initialized objects will always be
read only and protected from destruction.
I also have a use case for this, and have implemented it in a similar way to Yannis. We use it as a safety net - all devs know that they shouldn’t delete protected models, but there are some models (such as financial transactions) that we want to add a safety net to.
If this is a thing you need to do for legal / regulatory requirements, overriding a couple methods is NOT going to be sufficient - someone could always use:
ActiveRecord::Base.connection.execute(‘DELETE FROM protected_stuffs WHERE id = 42’)
to bypass all of those. If you really can’t allow a record to be deleted from that table, I’d suggest revoking that permission from the user your application connects to the database as.
In fact yea it would, I didn't know how much protection you needed, if you need to update the records then yea this wouldn't work for you, because every record you'd fetch would be protected.