Okechukwu Uneze
1 min readJan 28, 2021

Rendering Rails Nested Association using JSON-API

How to render a association using rails json-api.

First lets create a model Patient, Doctor, and a joiner table of Appointment

class Patient < ApplicationRecord
has_many :appointments
has_many :doctors, through: :appointments
end
class Doctor < ApplicationRecord
has_many : appointments
has_many : patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
end

Now that we have created our model to render them as a nested json we need to go to controller for each model create a method based on our routes. For now lets just use the resource routes provided rails. if we want to render a json Doctor to Patient association it would look like this below.

class ApplicationController < ActionController::APIendclass DoctorsController < ApplicationController
def show
doctor = Doctor.find(params[:id])
render json: doctor, include: ['patient']
end
end

For a Patient to Doctor association below

class PatientsController < ApplicationController
def show
patient = Patient.find(params[:id])
render json: patient, include: ['doctor']
end
end

The End