ActiveRecord 模型的意外序列化
我们引入了一个补丁,用于防止在未指定要序列化的字段的情况下意外序列化 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'
正确用法:
- 使用序列化器
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
这篇文档对你有帮助吗?
谢谢你的反馈!