我有一个模型应该呈现为JSON,为此我使用了一个序列化程序
class UserSerializer
def initialize(user)
@user=user
end
def to_serialized_json
options ={
only: [:username, :id]
}
@user.to_json(options)
end
end
当我CCD_ 1时,我希望添加JWT令牌和CCD_。不幸的是,我很难理解如何向上面的序列化程序添加属性。以下代码不起作用:
def create
@user = User.create(params.permit(:username, :password))
@token = encode_token(user_id: @user.id) if @user
render json: UserSerializer.new(@user).to_serialized_json, token: @token, errors: @user.errors.messages
end
这段代码只渲染=> "{"id":null,"username":""}"
,我如何添加属性token:
和errors:
来渲染类似的东西,但仍然使用序列化程序:
{"id":"1","username":"name", "token":"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.7NrXg388OF4nBKLWgg2tdQHsr3HaIeZoXYPisTTk-48", "errors":{}}
我可以使用
render json: {username: @user.username, id: @user.id, token: @token, errors: @user.errors.messages}
但是如何通过使用串行器来获得相同的结果呢?
class UserSerializer
def initialize(user)
@user=user
end
def to_serialized_json(*additional_fields)
options ={
only: [:username, :id, *additional_fields]
}
@user.to_json(options)
end
end
每次您想添加更多要序列化的新字段时,都可以执行类似UserSerializer.new(@user).to_serialized_json(:token, :errors)
的操作
如果为空,它将使用默认字段:id, :username
如果您希望添加的json是可自定义的
class UserSerializer
def initialize(user)
@user=user
end
def to_serialized_json(**additional_hash)
options ={
only: [:username, :id]
}
@user.as_json(options).merge(additional_hash)
end
end
UserSerializer.new(@user).to_serialized_json(token: @token, errors: @user.error.messages)
如果保留为空,它的行为仍然与您发布的原始类类似
将to_json更改为as_json,并合并新的键值。
class UserSerializer
def initialize(user, token)
@user=user
@token=token
end
def to_serialized_json
options ={
only: [:username, :id]
}
@user.as_json(options).merge(token: @token, error: @user.errors.messages)
end
end
我更喜欢使用一些序列化gem来处理像这样的序列化过程
jsonapi串行器https://github.com/jsonapi-serializer/jsonapi-serializer
或其他