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

后端 未结 8 1272
-上瘾入骨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:06

    TL;DR for OP's

    class YourModel < ActiveRecord::Base
      before_save { false } # prevent create & update, allows destroy
    
      # ... 
    end
    

    Generally

    • To prevent creates only: before_create { false }
    • To prevent updates only: before_update { false }
    • To prevent destroys only: before_destroy { false } # does not prevent delete

    See also: http://guides.rubyonrails.org/active_record_callbacks.html

提交回复
热议问题