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.
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…