Customize the JSON Response Using as_json:

To modify how Rails serializes the Apprenticeship object into JSON, you can use the as_json method to include the associated records (Jedi and Padawan) as nested objects.

class ApprenticeshipsController < ApplicationController
     def index
       # Load all apprenticeships with their associated Jedi and Padawan records
       @apprenticeships = Apprenticeship.includes(:jedi, :padawan).all
  
       # Render JSON with nested Jedi and Padawan information
       render json: @apprenticeships.as_json(
         include: {
           jedi: { only: [:id, :name] },
           padawan: { only: [:id, :name] }
         }
       )
     end
   end

 

Support On Demand!

Ruby on Rails