Rails Pattern For Including Nested Resources In API Responses

Dale Zak
4 min readMar 2, 2021

This Rails pattern provides a flexible way for clients to specify whether they want nested resources includes in the API response simply by passing a flag as a parameter to the endpoint.

For example if you were building a simple blog, you would get Posts with Comments by calling posts.json?comments=true, however calling posts.json or posts.json?comments=false would return Posts without Comments.

posts.json?comments=false
posts.json?comments=true

This is incredibly powerful giving the client the flexibility to consume lighter weight responses by default or make less requests by including nested resources when needed.

The trick to avoid N+1 queries is to use a scope which calls includes(:comments) when the flag is true. To achieve this the Posts and Comments models would be something like this.

class Post < ApplicationRecord
belongs_to :user, counter_cache: true
has_many :comments, -> { order(created_at: :desc)}, inverse_of: :post, dependent: :destroy
scope :with_comments…

--

--

Dale Zak

Full stack developer specializing in web apps built on Rails with Stimulus, and mobile apps using Ionic and Vue.