Eager load associations with Active Model Serializers

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

Background

I have a rails application with deeply nested associations.

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


        
2条回答
  •  青春惊慌失措
    2020-12-28 19:21

    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.

提交回复
热议问题