如何在自定义控制器操作中呈现jsonapi-resources响应?

时间:2017-11-06 07:43:30

标签: ruby-on-rails jsonapi-resources

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

成功创建后,我想显示创建的对象表示。

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

调用super方法也会触发默认的资源创建逻辑,所以这对我来说不起作用。

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

3 个答案:

答案 0 :(得分:0)

render json: JSON.pretty_generate( JSON.parse @transaction )

答案 1 :(得分:0)

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 }

答案 2 :(得分:0)

你可以这样做:

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

通过这种方式,您将获得符合Jjsonapi标准的json响应

相关问题