Skip to content

Commit 51f47bb

Browse files
authored
Merge pull request #4339 from nhsuk/flatten-exists
Flatten nested `EXISTS`
2 parents d52172b + 9e23b12 commit 51f47bb

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

app/models/patient_session.rb

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -93,26 +93,28 @@ class PatientSession < ApplicationRecord
9393

9494
scope :appear_in_programmes,
9595
->(programmes) do
96+
# Are any of the programmes administered in the session?
97+
programme_in_session =
98+
SessionProgramme
99+
.where(programme: programmes)
100+
.where("session_programmes.session_id = sessions.id")
101+
.arel
102+
.exists
103+
96104
# Is the patient eligible for any of those programmes by year group?
97-
location_programme_year_groups =
105+
patient_in_administered_year_groups =
98106
LocationProgrammeYearGroup
99-
.where("programme_id = session_programmes.programme_id")
107+
.where(programme: programmes)
100108
.where("location_id = sessions.location_id")
101109
.where(
102110
"year_group = sessions.academic_year " \
103111
"- patients.birth_academic_year " \
104112
"- #{Integer::AGE_CHILDREN_START_SCHOOL}"
105113
)
106-
107-
# Are any of the programmes administered in the session?
108-
where(
109-
SessionProgramme
110-
.where(programme: programmes)
111-
.where("session_programmes.session_id = sessions.id")
112-
.where(location_programme_year_groups.arel.exists)
113114
.arel
114115
.exists
115-
)
116+
117+
where(programme_in_session).where(patient_in_administered_year_groups)
116118
end
117119

118120
scope :search_by_name,

0 commit comments

Comments
 (0)