与主动模型序列化程序的急切加载关联 [英] Eager load associations with Active Model Serializers

查看:23
本文介绍了与主动模型序列化程序的急切加载关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有深度嵌套关联的 Rails 应用程序.

I have a rails application with deeply nested associations.

                          .-< WorkPeriod
Timecard -< Week -< Day -<--< Subtotal
                          `-< Adjustment

-<  (has many)

我正在使用 Active Model Serializer 来构建 API.

I'm using Active Model Serializer to build out the API.

在客户端,我想一次性加载考勤卡及其所有关联.

On the client side I want to load a timecard and all it's associations in one shot.

目前我的序列化器看起来像这样,

Currently my serializers look like this,

class TimecardSerializer < ActiveModel::Serializer
  embed :ids, include: true
  has_many :weeks
end
class WeekSerializer < ActiveModel::Serializer
  embed :ids, include: true
  has_many :days
end
# ... etc ...

问题

这一切都可以找到,除了没有任何东西被急切加载.因此,它最终会为每个请求对数据库进行大量调用.对于每一周,它会针对该周的天数发出单独的请求.对于每一天,它都会对其工作周期、小计和调整提出单独的请求.

Problem

This all works find, except nothing gets eager-loaded. So it ends up making lots of calls to the database for each request. For each week, it makes a separate request for the days in that week. And for each day, it makes a separate request for it's work_periods, subtotals, and adjustments.

推荐答案

一种解决方案是在 TimecardSerializer 上定义您自己的 weeks 方法.从那里你可以.includes()你想要立即加载的所有关联.

One solution is to define your own weeks method on the TimecardSerializer. From there you can .includes() all the associations you want to eager load.

class TimecardSerializer < ActiveModel::Serializer
  embed :ids, include: true
  has_many :weeks

  def weeks
    object.weeks.includes(days: [:sub_totals, :work_periods, :adjustments])
  end
end

所有查询仍会显示在日志中,但大多数将是缓存查询而不是真实查询.

All the queries will still show up in the log but most will be a cached query instead of a real one.

这篇关于与主动模型序列化程序的急切加载关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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