I would like to protect my model in production of of being deleted

It would be nice if rails provide this functionality by default ?

I don’t know if there is a functionality like this already but for me its something fundamental

If there is i couldn’t find nothing till now

Of Course there is the soft delete but this is a different concept

I dont know if my concept its valid or not or whats the gotchas but why protected_attributes and not protected_model?

require “active_record”
require ‘active_record/errors’

module ActiveRecord

class ProtectedModelError < ActiveRecordError #:nodoc:
def initialize
super(“Cannot delete record because its protected”)

module ProtectedModel
extend ActiveSupport::Concern

def delete(*args)

def destroy_all(*args)

def destroy(*args)

module ClassMethods
  def delete_all(*args)



class Query < ActiveRecord::Base
include ActiveRecord::ProtectedModel if Rails.env.production?


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.

—Matt Jones

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.

Thanks for your replies guys

As you sayed Matt jones yes they can execute queries like this!

This is a quick example just to show you want i mean!

Mohammad AbuShady: i dint try default_scope readonly! I dont know if this the official functionality and a hackie one to protect a model

Ryan Bigg: To protect it from any type of concept like rake task, sql queries execution, controllers etc!

I just wanna be sure somehow that this model CAN NOT be deleted from rails app!

Ok if some had access to my db and delete it this is another thing!

i dont want to use cancan any plug in like this!

I want to say

this is my Language model and no one can; t delete it!

This is financial transaction model no one can; t delete it!