Is there an easy way to make a Rails ActiveRecord model read-only?

后端 未结 8 1366
-上瘾入骨i
-上瘾入骨i 2021-01-31 01:25

I want to be able to create a record in the DB but then prevent Rails from making changes from that point on. I understand changes will still be possible at the DB level.

8条回答
  •  不要未来只要你来
    2021-01-31 02:03

    This seems to be fairly effective and is probably a bit overkill, but for my case, I really want to be sure my application will never create, save, update, or destroy any records in the model, ever.

    module ReadOnlyModel
      def readonly?() true end
      def create_or_update() raise ActiveRecord::ReadOnlyRecord end
      before_create { raise ActiveRecord::ReadOnlyRecord }
      before_destroy { raise ActiveRecord::ReadOnlyRecord }
      before_save { raise ActiveRecord::ReadOnlyRecord }
      before_update { raise ActiveRecord::ReadOnlyRecord }
    end
    
    class MyModel < ActiveRecord::Base
      include ReadOnlyModel
      # ...
    end
    

    Since OP asked to be able to create and destroy but not save or update I believe this will work

    module SaveAndDestroyOnlyModel
      before_save { raise ActiveRecord::ReadOnlyRecord }
      before_update { raise ActiveRecord::ReadOnlyRecord }
    end
    
    class MyModel < ActiveRecord::Base
      include SaveAndDestroyOnlyModel
      # ...
    end
    

    Not exactly the right exception, but close enough I think.

提交回复
热议问题