Skip to content

Commit c4c75df

Browse files
committed
Optimise GET api/v2/plans / Fix N+1 queries
This change further addresses Bullet warnings that were earlier addressed in commit 6ed969b
1 parent 2d95cd2 commit c4c75df

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

app/models/plan.rb

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -211,16 +211,34 @@ class Plan < ApplicationRecord
211211
includes(:phases, :sections, :questions, template: [:org]).find(id)
212212
}
213213

214+
# Eager loads all associations needed for API v2 serialization,
215+
# and restricts to plans where the user_id has an active role.
214216
scope :for_api_v2, lambda { |user_id|
215217
joins(:roles)
216218
.includes(
217-
:identifiers,
218219
:research_outputs,
219220
:template,
220-
funder: :identifiers,
221-
contributors: [:identifiers, { org: :identifiers }],
222-
org: %i[region identifiers],
223-
roles: [user: [:identifiers, { org: :identifiers }]]
221+
{ identifiers: :identifier_scheme },
222+
funder: { identifiers: :identifier_scheme },
223+
contributors: [
224+
{ identifiers: :identifier_scheme },
225+
{ org: { identifiers: :identifier_scheme } }
226+
],
227+
roles: [
228+
user: [
229+
:language,
230+
{ identifiers: :identifier_scheme },
231+
{ org: { identifiers: :identifier_scheme } }
232+
]
233+
],
234+
# plan.org is only executed when `plan.funder.present? || plan.grant_id.present? == true`
235+
# - (see `app/views/api/v2/plans/_project.json.jbuilder`)
236+
# Thus, the following line avoids N+1 queries in some cases,
237+
# but performs unnecessary eager loading in others
238+
org: [
239+
:region,
240+
{ identifiers: :identifier_scheme }
241+
]
224242
)
225243
.where(roles: { user_id: user_id, active: true })
226244
.distinct

0 commit comments

Comments
 (0)