How to render a jsonapi-resources response in an custom controller action?

爷,独闯天下 提交于 2019-12-04 12:51:45

You could do something like this:

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

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

render json: JSON.pretty_generate( JSON.parse @transaction )
def render_json
  result =
    begin
      block_given? ? { success: true, data: yield } : { success: true }
    rescue => e
      json_error_response(e)
    end

  render json: result.to_json
end

def json_error_response(e)
  Rails.logger.error(e.message)

  response = { success: false, errors: e.message }

  render json: response.to_json
end

render_json { values }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!