如果包含在哈希中,则不使用序列化程序
serializer is not beeing used if included in a hash
ActiveModelSerializers.config.default_includes = '**'
我们通过序列化程序呈现评论,包括作者和一些信息。
这是在使用序列化器,一切正常
render json: comments
但是,我们还需要发送额外的元数据,因此我们将其包装到哈希中。不幸的是,这没有使用序列化器,我们无法弄清楚为什么
render json: {comments: comments, upvoted: upvoted, downvoted: downvoted}
您可能想要的是在元数据中包含赞成票和反对票的属性。要将赞成票和反对票的属性作为元数据包含在内,您必须使用 json 或 json_api 适配器。在你的控制器中有这个:
render json: comments, meta: { upvoted: upvoted, downvoted: downvoted }, adapter: :json
将呈现:
{
"comments": [
// your comments...
],
"meta": {
"upvoted": 4243,
"downvoted": 123
}
}
或者您可以只为此响应创建一个模型,其中包含评论以及赞成票和反对票的属性。
根据git
https://github.com/rails-api/active_model_serializers/issues/2102#issuecomment-293292697
如果我们渲染一个散列而不是一个集合,就不可能自动使用序列化程序。解决方法是
json = Hash.new
json[:comments] = ActiveModel::SerializableResource.new(comments)
json[:upvoted] = upvoted
json[:downvoted] = downvoted
render status: :ok, json: json
ActiveModelSerializers.config.default_includes = '**'
我们通过序列化程序呈现评论,包括作者和一些信息。
这是在使用序列化器,一切正常
render json: comments
但是,我们还需要发送额外的元数据,因此我们将其包装到哈希中。不幸的是,这没有使用序列化器,我们无法弄清楚为什么
render json: {comments: comments, upvoted: upvoted, downvoted: downvoted}
您可能想要的是在元数据中包含赞成票和反对票的属性。要将赞成票和反对票的属性作为元数据包含在内,您必须使用 json 或 json_api 适配器。在你的控制器中有这个:
render json: comments, meta: { upvoted: upvoted, downvoted: downvoted }, adapter: :json
将呈现:
{
"comments": [
// your comments...
],
"meta": {
"upvoted": 4243,
"downvoted": 123
}
}
或者您可以只为此响应创建一个模型,其中包含评论以及赞成票和反对票的属性。
根据git
https://github.com/rails-api/active_model_serializers/issues/2102#issuecomment-293292697
如果我们渲染一个散列而不是一个集合,就不可能自动使用序列化程序。解决方法是
json = Hash.new
json[:comments] = ActiveModel::SerializableResource.new(comments)
json[:upvoted] = upvoted
json[:downvoted] = downvoted
render status: :ok, json: json