Remove N+1 query for Noteable association.

For each event with `Event#target_type` of "Note",
we had a query to load the associated instance `noteable`.

For example, if `Note` was related to an issue, we'd load each `Issue`
with its own query (N+1 problem).

Closes #43150.
This commit is contained in:
Andreas Brandl 2018-03-23 13:58:46 +01:00
parent 3cd95700d4
commit 783868e9fa
2 changed files with 10 additions and 5 deletions

View File

@ -52,12 +52,12 @@ class Event < ActiveRecord::Base
belongs_to :target, -> {
# If the association for "target" defines an "author" association we want to
# eager-load this so Banzai & friends don't end up performing N+1 queries to
# get the authors of notes, issues, etc.
if reflections['events'].active_record.reflect_on_association(:author)
includes(:author)
else
self
# get the authors of notes, issues, etc. (likewise for "noteable").
incs = %i(author noteable).select do |a|
reflections['events'].active_record.reflect_on_association(a)
end
incs.reduce(self) { |obj, a| obj.includes(a) }
}, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
has_one :push_event_payload

View File

@ -0,0 +1,5 @@
---
title: Remove N+1 query for Noteable association.
merge_request: 17956
author:
type: performance