I am struggling to find the best way to render records. So far, I did it the following way but, despite having includes when I fetch the main object, I get tons of DB queries when calling as_json for the child record that was included. What am I missing? Is there even a better way too do what I want to do?
I don't see how to have a better render since I want to decide what attributes and methods to serialise and use custom scopes on arrays of associate records.
- My controller
def show
# The include below seems to be useless, the DB is queried again on render.
@grandParent = GrandParent.includes(parents: { children: %i[grand_children friends] })
.find_by_name(params[:name])
return head :not_found unless @grandParent
render json: grand_parent_as_json, status: :ok
end
private
def grand_parent_as_json
json = @grandParent.as_json(
only: %i[attr1 attr2],
methods: %i[meth1 meth2]
)
# I don't see a better way to render it since I want to use a custom scope on parents
json[:parents] = @grandParent.parents.ordered_by_birthdate(:desc).map do |parent|
parent_as_json parent
end
json
end
# The include below seem to be the one responsible for querying the DB again.
def parent_as_json(parent)
parent.as_json(
only: %i[attr1 attr2],
methods: %i[meth1 meth2],
include: [
children: {
only: %i[attr1 attr2],
include: [
grand_children: { %i[attr1 attr2] }
]
}
]
)
end