如何在 active_model_serializers 中执行预先加载 [英] How to perform eager loading in active_model_serializers

查看:41
本文介绍了如何在 active_model_serializers 中执行预先加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多层嵌套关联的模型.例如,

I have a model with several layers of nested associations. e.g.,

ModelA has_many: model_b
ModelB has_one : model_c
ModelC has_many: model_d
ModelD has_many: model_e
  ...

在序列化器中,embed :ids, include: true 用于旁加载:

In serializers, embed :ids, include: true is used for sideloading:

class ModelASerializer < ActiveModel::Serializer
    embed :ids, include: true

    has_many: model_b

    attributes: ...
end

class ModelBSerializer < ActiveModel::Serializer
    embed :ids, include: true
    ...

当model_a被渲染时,它有一个严重的n+1问题",并且会产生成千上万的调用,比如:

When model_a is rendered, it has a serious "n+1 problem" and will generate thousands of calls like:

    ModelC Load (0.3ms)  SELECT "model_cs".* FROM "model_cs" WHERE "model_cs"."id" = $1 LIMIT 1  [["id", "2060c506-8c9c-4d1c-a64c-62455fa18bc4"]]
    CACHE (0.0ms)  SELECT "model_ds".* FROM "model_ds" WHERE "model_ds"."id" = $1 LIMIT 1  [["id", "2e36f19f-25e1-4953-99ba-f8c0271106dd"]]
    CACHE (0.0ms)  SELECT "model_es".* FROM "model_es" WHERE "model_es"."id" = $1 LIMIT 1  [["id", "31e53b55-6df6-44cd-98ad-2011cced1e1a"]]

即使明确指定了包含,它似乎也没有效果:

Even if the includes are specified explicitly it doesn't seem to have an effect:

render json: ModelA.includes(:model_bs => [:model_c =>[:model_ds => [:model_es]]])

active_model_serializers 文档说你应该使用预先加载,但没有指定他们打算如何完成.是否必须在序列化程序中指定包含?如果是这样,如何?

The active_model_serializers documentation says you should use eager loading but doesn't specify how they intend it to be done. Do the includes have to be specified in the serializer? If so, how?

推荐答案

这是一个很好的描述和解释.这就是你要找的?

This is a good description and explanation. This is what you're looking for?

class ModelName
  default_scope includes(:other)
end

如何将 `:include` 添加到 default_scope?

我没有像您那样在一系列模型中完成此操作,我已经使用序列化程序通过一个级别完成了此操作,并且我还使用了 jbuilder 来减轻痛苦并通过 2 个级别来利用控制.我仍然相信你想把这层控制放在模型级别.

I haven't done this in a nest of models like you have, I have done this through one level using serializers, and I've also used jbuilder to ease the pain and leverage control through 2 levels. I still believe you want to put this layer of control on the model level though.

这篇关于如何在 active_model_serializers 中执行预先加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆