Search code examples
ruby-on-railsrails-api

How do I include a newly created model object in my Rails API response to a post request?


I have a Rails API that successfully processes the data it receives via a Post request. In the controller for the create action, I have this code for my response:

render json: project, status: 201

But my response doesn't include project and looks like this:

Response {type: "basic", url: "http://localhost:3000/api/save", redirected: false, status: 201, ok: true, …}body: (...)bodyUsed: falseheaders: Headers__proto__: Headersok: trueredirected: falsestatus: 201statusText: "Created"type: "basic"url: "http://localhost:3000/api/save"__proto__: ResponsearrayBuffer: ƒ arrayBuffer()blob: ƒ blob()body: (...)bodyUsed: (...)clone: ƒ clone()formData: ƒ formData()headers: (...)json: ƒ json()arguments: (...)caller: (...)length: 0name: "json"__proto__: ƒ ()[[Scopes]]: Scopes[0]ok: (...)redirected: (...)status: (...)statusText: (...)text: ƒ text()arguments: (...)caller: (...)length: 0name: "text"__proto__: ƒ ()[[Scopes]]: Scopes[0]type: (...)url: (...)constructor: ƒ Response()Symbol(Symbol.toStringTag): "Response"get body: ƒ ()get bodyUsed: ƒ ()get headers: ƒ ()get ok: ƒ ()get redirected: ƒ ()get status: ƒ ()get statusText: ƒ ()get type: ƒ ()get url: ƒ ()__proto__: Object

How can I include the model object in the response to the Post request, so that I can use it on the frontend without making another request?


Solution

  • First, make sure that your Request in routes.rb has the {:format => :json} as below in case your response is usually in JSON format:

    post 'create_item' => 'items#create', as: 'public_holidays_by_year', :defaults => {:format => :json}
    

    Second, you need to define the parameter that will carry the project data as below:

    render json: {status: 201, project: project}
    

    OR

    render json: project 
    

    In last option, no need to define status 201 as it will be created automatically by rails for the create request, check below link:
    https://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option