Seems like you need to to use an outer join
. Rails implements this with includes
or eager_load
.
In your case you can have
@contracts = Contract.a_desired_scope.includes(:appointments)
then
@contracts.to_json
will only require one query to fetch all contracts with their relevant appointments.
instead of to_json
you can use whatever iterating method you want, without affecting the number of queries.
In your case you can have a to_json
method for each model
#apointment.rb
def to_json
desired_attributes_hash.to_json
end
and
#contract.rb
def to_json
{
id: id
apointments: apointments.map(&:to_json)
}
end