I have a model questions that has many tags through another model question_tags. I am trying to write an api endpoint that returns a list of questions and for each question a list of it’s related tag’s name and id.
I’m currently using;
x
render json: @questions.as_json(include: {
tags: { only: %i[id name] }
})
But this runs a separate db request for every question in questions is there an alternative that will result in a smaller number of database requests?
Advertisement
Answer
The standard N+1 queries fixes should work here, which in Rails is eager loading.
In this case you can use include
to preload the associated tags
:
render json: @questions.includes(:tags).as_json(
include: {
tags: { only: %i[id name] }
}
)
You can read more about this in the dedicated rails guide section: Eager Loading Associations