I have a rails application with deeply nested associations.
.-< WorkPeriod
Timecard -< Week -< Day -&
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.
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.