Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid multiple SQL calls in ActiveModel Serializers?

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

I've tried to do an include in the controller:

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

But this does not seem to work. Even if I pass the relation (with includes) directly to ArraySerializer it doesn't help.

like image 891
Brandon Avatar asked Jul 28 '13 19:07

Brandon


1 Answers

It is a bit radical but for complex queries which were being hit a lot I moved the whole JSON generation into the database query (I'm using Postgres 9.3 which supports that). It probably isn't the cleanest solution as it needs pretty raw SQL but it is fast.

I'll update with an example if anyone is interested.

like image 185
Joseph Lord Avatar answered Oct 22 '22 01:10

Joseph Lord