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

后端 未结 8 1420
-上瘾入骨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 01:52

    A custom validator can do this:

    validate :nothing_changed, unless: :new_record? # make immutable
    
    ...
    
    def nothing_changed
      errors.add(:base, "Record is read-only") if self.changed?
    end
    

提交回复
热议问题