Rails 讓 ActiveRecord model 只能在特定 service class 裏被更新

mizuhashi · 2026年05月22日 · 21 次阅读
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

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号