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

 

Need Help With Ruby On Rails Development?

Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.

Hire Ruby on Rails Developer

Support On Demand!

Related Q&A