From 59e5dd2479ae51e42b33ab588fb592aa0bc7febb Mon Sep 17 00:00:00 2001 From: Theodor Vararu Date: Tue, 17 Dec 2024 09:45:06 +0000 Subject: [PATCH] Remove N+1 on register attendance page 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`. --- .../register_attendances_controller.rb | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/app/controllers/register_attendances_controller.rb b/app/controllers/register_attendances_controller.rb index 5995c5139..6e2471083 100644 --- a/app/controllers/register_attendances_controller.rb +++ b/app/controllers/register_attendances_controller.rb @@ -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" @@ -41,19 +41,21 @@ def set_session end def set_patient_sessions - @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 = @session + .patient_sessions + .strict_loading + .includes( + :patient, + :vaccination_records, + :triages, + :consents, + session: :session_dates, + session_attendances: :session_date + ) + + @patient_sessions = ps + .where.missing(:session_attendances) + .or(ps.where.not(session_attendances: { session_date: @session_date })) end def set_patient