Rails Serializer - Access grandparent

Viewed 16

Given this example:

class School
  has_many :teachers
end
class Teacher
  belongs_to :school
  has_many :students
end
class Student
  belongs_to :teacher
  delegate :school, to: :teacher, allow_nil: true
end

I can easily access School with Student.first.school but how can I do it with JSONAPI::Serializer?

Is it possible to have a Serializer where student.school is possible?

1 Answers

Just use an indirect assocation instead of delegation:

class Student < ApplicationRecord
  belongs_to :teacher
  has_one :school, through: :teacher
end

class StudentSerializer 
  include JSONAPI::Serializer
  has_one :school
end
Related