Galet
Galet

Reputation: 6289

How to add additional attributes to the JSON response in my Rails API

I am using Rails 5.2 for my application.

Request:

http://localhost:3000/reports

Response:

[
    {
        id: 1,
        name: "Ram",
        details: {
            path: "dev/daily_summary_20190503.csv",
            success_detail: "Report uploaded to S3"
        },
        status: "success"
    },
    {
        id: 2,
        name: "John",
        details: {
            path: "dev/daily_summary_20190504.csv",
            error_detail: "Error in uploading report. Refer log for details"
        },
        status: "failed"
    }
]

I want to add download_url, message parameters to every records where parameters is not added to schema. Following is my expected output,

Expected output:

[
    {
        id: 1,
        name: "Ram",
        details: {
            path: "dev/daily_summary_20190503.csv",
            success_detail: "Report uploaded to S3"
        },
        status: "success",
        download_url: "https://<S3_HOST>/dev/daily_summary_20190503.csv",
        message: "Report uploaded to S3"
    },
    {
        id: 2,
        name: "John",
        details: {
            error_detail: "Error in uploading report. Refer log for details"
        },
        status: "failed",
        message: "Error in uploading report. Refer log for details"
    }
]

I have tried using attr_accessor, but which doesn't help me to display download_url in all records of index method in controller.

How can I add the paramters for index and show of every records?

Upvotes: 0

Views: 989

Answers (1)

bjelli
bjelli

Reputation: 10090

If you want to change the JSON that is in the HTTP response you need to find the place where the JSON is generated. Follow the trail from the request URL:

  • use rails routes on the command line
  • in the outbut, find your url /reports and read which controller + action it is mapped to
  • open the controller file (probably /app/controllers/reports_controller.rb) and find the action (probably index)
  • look at the end of the action

If you find a render statement like this:

  respond_to do |format|
    format.html  # index.html.erb
    format.json  { render :json => @reports }
  end

you need to follow the block after format.json. In this example you see that the data that is displayed is stored in the @reports variable. study the action to find out how the data is created. The data is then rendered using the template /app/views/reports/index.json.jbuilder. Read up on jbuilder.

In a more complex application instead of jbuilder ActiveModelSerializer might be used.

Upvotes: 1

Related Questions