How to avoid multiple SQL calls in Serializer ActiveModel?

I find that when I use ActiveModel serializers to generate JSON for a set of models that include associations, this results in a ton of SQL queries (one for each association). How can i avoid this?

I tried to include include in the controller:

render json: Project.includes(tasks: [:workers]) 

But this does not seem to work. Even if I pass the relation (with it turned on) directly to the ArraySerializer, this will not help.

+6
source share
5 answers

This is a bit radical, but for complex queries that hit hard, I moved the entire JSON generator to a database query (I use Postgres 9.3, which supports this). This is probably not the cleanest solution since it needs pretty simple SQL, but it is fast.

I will update the example if anyone is interested.

+1
source

according to the documentation [1], you are doing everything right. The serializer just takes care of serializing the object. Therefore, you will need to download everything you need before calling the serializer.

1 - https://github.com/rails-api/active_model_serializers#performance

0
source

Try creating the instance yourself:

 @projects = Project.includes(tasks: [:workers]) render json: ActiveModel::ArraySerializer.new(@projects, each_serializer: ProjectSerializer).to_json 
0
source

I found that using inclusions in the controller worked for me, but you have to be careful that your serializer object does not include relationships that are not included in include.

I also found that if you specify a one-to-one relationship, for example

 has_one :country, embed: :ids, include: false 

he will retrieve another object, even if he does not need it. Instead, I replaced it with:

 attributes :country_id 

I am using Serializer Active Model v0.8.3

0
source

I switched to rabl. more granular and better control

-1
source

Source: https://habr.com/ru/post/950481/


All Articles