Change json format output in Rails?

Asked

Viewed 82 times

0

I have an API that has the data in the following format:

[
{
    "id": 1,
    "vehicle": "350",
    "code": "350",
    "delivery_date": "2019-07-26T00:00:00.000Z",
    "created_at": "2019-08-07T17:00:37.000Z",
    "updated_at": "2019-08-07T17:00:37.000Z"
},
{
    "id": 2,
    "vehicle": "364",
    "code": "364",
    "delivery_date": "2019-07-26T00:00:00.000Z",
    "created_at": "2019-08-07T17:00:37.000Z",
    "updated_at": "2019-08-07T17:00:37.000Z"
},
{
    "id": 3,
    "vehicle": "1305",
    "code": "1305",
    "delivery_date": "2019-07-26T00:00:00.000Z",
    "created_at": "2019-08-07T17:00:37.000Z",
    "updated_at": "2019-08-07T17:00:37.000Z"
},
]

The point is that because of (I believe) the " [ ] " url/api/loads/list/1

just how do I change this output?

@loads = Load.all
        render json: @loads, status: 200

That’s actually what I have.

  • The output is so pq Load.all returns a list of "load", if you want to return only one element you have to find render json: Load.find(params[:id]), status: 200

1 answer

0

You cannot do this. You have created an output for your list index, which shows all of them. If you want to create an endpoint to show a specific item, create a show route.

def show
  @load = Load.find(params[:id])
  render json: @load, status: 200
end

namespace :api do
  namespace :v1 do
    resources :loads, only: [:index, :show]
  end
end

Remembering that this api and v1 are only good API practices, the only thing needed to work is to create an endpoint show.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.