我们引入了一个补丁,以防止在未指定要序列化的字段的情况下意外序列化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 上建议更改。