我们引入了一个补丁,以防止在未指定要序列化的字段的情况下意外序列化 ActiveRecord 模型。此更改确保我们能够控制包含哪些字段,从而避免潜在的数据不完整或数据过度暴露的问题。
默认情况下,将 ActiveRecord 模型渲染为 JSON 时会包含所有属性,但在许多情况下这可能并非所期望的。为了强制采用更好的实践,我们需要指定应该序列化哪些字段。
使用示例
错误用法:
def show
@user = User.first
render json: @user
end
在开发和测试环境中,这将导致以下错误:
ActiveRecordSerializationSafety::BlockedSerializationError:
Serializing ActiveRecord models (User) without specifying fields is not allowed.
Use a Serializer, or pass the :only option to #serializable_hash. More info: https://meta.discourse.org/t/-/314495
./lib/freedom_patches/active_record_disable_serialization.rb:15:in `serializable_hash'
正确用法:
- 使用序列化器 (Serializer)
class UserSerializer < ApplicationSerializer
attributes :id, :email
end
def show
@user = User.first
render json: @user, serializer: UserSerializer
end
- 使用
:only选项
def show
@user = User.first
render json: @user.as_json(only: [:id, :email])
end
本文档受版本控制 - 如有修改建议,请在 GitHub 上提出。