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 で行ってください。