与主动型串行器贪婪加载协会 [英] Eager load associations with Active Model Serializers
问题描述
我有一个深度嵌套协会的Rails应用程序。
I have a rails application with deeply nested associations.
.-< WorkPeriod
Timecard -< Week -< Day -<--< Subtotal
`-< Adjustment
-< (has many)
我使用活动模型串行打造出来的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 ...
问题
这所有的作品找到,但没有得到渴望加载。因此,最终使很多调用数据库为每个请求。对于每个星期,它使得在一个星期的日子里单独的请求。而对于每一天,它使得它的work_periods,小计和调整独立的要求。
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自己的周
方法。从那里你可以 .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屋!