本文介绍了如何在自定义控制器操作中呈现jsonapi-resources响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过重写JSONAPI :: ResourceController控制器中的create动作来实现自己的对象创建逻辑.

I have implemented my own object creation logic by overriding the create action in a JSONAPI::ResourceController controller.

成功创建后,我要呈现创建的对象表示形式.

After successful creation, I want to render the created object representation.

如何使用jsonapi-resources gem呈现此自动生成的JSON API响应?

调用super方法也会触发默认的资源创建逻辑,因此这对我来说不可行.

Calling the super method does also trigger the default resource creation logic, so this does not work out for me.

class Api::V1::TransactionsController < JSONAPI::ResourceController
  def create
    @transaction = Transaction.create_from_api_request(request.headers, params)

    # render automatic generated JSON API response (object representation)
  end
end

推荐答案

您可以执行以下操作:

class UsersController < JSONAPI::ResourceController
  def create
    user = create_user_from(request_params)

    render json: serialize_user(user)
  end

  def serialize_user(user)
    JSONAPI::ResourceSerializer
            .new(UserResource)
            .serialize_to_hash(UserResource.new(user, nil))
  end
end

这样,您将获得符合Jsonapi标准的json响应

this way you will get a json response that is compliant with Jsonapi standards

这篇关于如何在自定义控制器操作中呈现jsonapi-resources响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 12:04