Eager load associations with Active Model Serializers

后端 未结 2 774
误落风尘
误落风尘 2020-12-28 18:43

Background

I have a rails application with deeply nested associations.

                          .-< WorkPeriod
Timecard -< Week -< Day -&         


        
2条回答
  •  猫巷女王i
    2020-12-28 19:35

    I had a similar issue. I fixed it in my controller. I like the idea of putting it in the serializer, but having it in the controller catches the n+1 weeks problem created by the ArraySerializer too.

    Timecard.find(params[:id]).includes(weeks: [{ days: [:sub_totals, :work_periods, :adjustments] }])
    

    and

    Timecard.includes(weeks: [{ days: [:sub_totals, :work_periods, :adjustments] }])
    

    should now eager load and limit the query to just six db hits.

提交回复
热议问题