3

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.

How to render this automatically generated JSON API response, using the jsonapi-resources gem?

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
Laugslander
  • 386
  • 2
  • 16

3 Answers3

3

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

beniutek
  • 1,672
  • 15
  • 32
0
render json: JSON.pretty_generate( JSON.parse @transaction )
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 }
Safi Nettah
  • 1,160
  • 9
  • 15
  • 1
    This does render a JSON response, but it's just plain JSON. It doesn't conform to the JSON API standard. The jsonapi-resources gem automatically generates rich JSON API respones (with links, attributes and relationships). – Laugslander Nov 06 '17 at 10:05
  • Oh sorry I misunderstood the question, I do not know this gem – Safi Nettah Nov 06 '17 at 10:14