class Post < ApplicationRecord
include ActiveRecordReadOnly
end
# Anywhere else in the codebase — blocked
Post.find(1).update!(title: "x")
# => ActiveRecord::ReadOnlyRecord
# In a service class — allowed
class PostService
include Post::Writable
def self.publish(post)
post.update!(published: true) # works
end
end
實驗後發現這是可行的,可以通過在 model 的readonly?方法裏檢查caller_locations來判斷能否處在一個已經include Post::Writable的環境,不過也有不少限制。
https://github.com/onyxblade/active_record_read_only
Just for fun