[英]active_model_serializers, includes, and why a serializer is querying data?
When working with API, I am used to: 使用API时,我习惯于:
Now , using active_model_serializers , I was assuming that in 现在 ,使用active_model_serializers ,我假设
render json: artist, include: 'tracks'
the include: 'tracks'
part would serialize tracks
, if my artist had some tracks. include: 'tracks'
部分将序列化tracks
(如果我的艺术家有曲目)。
But apparently, it will also fetch the tracks from the db for me. 但显然,它也将为我从数据库中获取曲目。
Is it a normal behaviour ? 这是正常现象吗? Is the serializer supposed to make db queries ?
序列化程序是否应该进行数据库查询?
Yes, to include a association it first has to be fetched from the database. 是的,要包含一个关联,首先必须从数据库中获取它。 Otherwise how can it be included in the response?
否则如何将其包含在响应中?
See the json serializer documentation . 请参阅json序列化器文档 。
The association is called by it's corresponding method. 关联是通过其相应的方法调用的。 In your example that would be Artist#tracks .
在您的示例中,将是Artist#tracks 。 (See the source code .) This means that if you load the association before calling the serializer it will not call the database.
(请参阅源代码 。) 这意味着,如果在调用序列化程序之前加载了关联,则不会调用数据库。
Example: 例:
artist = Artist.first # <= artists table gets queried
artist.tracks.load # <= tracks table gets queried
render json: artist, include: :tracks # <= no queries
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.