Skip to content

Commit

Permalink
Remove N+1 on register attendance page
Browse files Browse the repository at this point in the history
The `.select` was causing a query for `session_attendances` based on
today's `@session_date`.

Instead, we can more directly use two `where` clauses:

- Either for patient sessions with no attendances
- Or for patient sessions with attendances but not on today's date

The patient sessions need to be stored in an intermediate `ps` variable
to maintain the joins from `includes` when using `.or`.
  • Loading branch information
tvararu committed Dec 17, 2024
1 parent 5126a40 commit ddbd6b9
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions app/controllers/register_attendances_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ class RegisterAttendancesController < ApplicationController
include PatientSortingConcern

before_action :set_session, only: %i[index create]
before_action :set_session_date
before_action :set_patient_sessions, only: :index
before_action :set_patient, only: :create
before_action :set_session_date, only: :create
before_action :set_patient_session, only: :create

layout "full"
Expand Down Expand Up @@ -41,19 +41,21 @@ def set_session
end

def set_patient_sessions
ps =
@session.patient_sessions.strict_loading.includes(
:patient,
:vaccination_records,
:triages,
:consents,
session: :session_dates,
session_attendances: :session_date
)

@patient_sessions =
@session
.patient_sessions
.strict_loading
.includes(
:patient,
:vaccination_records,
:triages,
:consents,
session: :session_dates,
session_attendances: :session_date
)
.select { _1.todays_attendance&.attending.nil? }
ps
.where
.missing(:session_attendances)
.or(ps.where.not(session_attendances: { session_date: @session_date }))
end

def set_patient
Expand Down

0 comments on commit ddbd6b9

Please sign in to comment.