@@ -66,24 +66,34 @@ class PatientLocation < ApplicationRecord
66
66
AND sessions.academic_year = patient_locations.academic_year
67
67
SQL
68
68
69
- scope :joins_session_programmes , -> { joins ( <<-SQL ) }
70
- INNER JOIN session_programmes
71
- ON session_programmes.session_id = sessions.id
72
- SQL
73
-
74
- scope :joins_location_programme_year_groups , -> { joins ( <<-SQL ) }
75
- INNER JOIN location_programme_year_groups
76
- ON location_programme_year_groups.location_id = patient_locations.location_id
77
- AND location_programme_year_groups.programme_id = session_programmes.programme_id
78
- AND location_programme_year_groups.year_group = patient_locations.academic_year - patients.birth_academic_year - #{ Integer ::AGE_CHILDREN_START_SCHOOL }
79
- SQL
80
-
81
69
scope :appear_in_programmes ,
82
70
-> ( programmes ) do
83
- joins_sessions
84
- . joins_session_programmes
85
- . joins_location_programme_year_groups
86
- . where ( session_programmes : { programme_id : programmes . map ( &:id ) } )
71
+ session_programme_exists =
72
+ SessionProgramme
73
+ . where ( programme : programmes )
74
+ . joins ( :session )
75
+ . where ( "sessions.location_id = patient_locations.location_id" )
76
+ . where ( "sessions.academic_year = patient_locations.academic_year" )
77
+ . arel
78
+ . exists
79
+
80
+ location_programme_year_group_exists =
81
+ LocationProgrammeYearGroup
82
+ . where (
83
+ "location_programme_year_groups.location_id = patient_locations.location_id"
84
+ )
85
+ . where (
86
+ "location_programme_year_groups.year_group = " \
87
+ "patient_locations.academic_year - patients.birth_academic_year - ?" ,
88
+ Integer ::AGE_CHILDREN_START_SCHOOL
89
+ )
90
+ . where ( programme : programmes )
91
+ . arel
92
+ . exists
93
+
94
+ where ( session_programme_exists ) . where (
95
+ location_programme_year_group_exists
96
+ )
87
97
end
88
98
89
99
scope :destroy_all_if_safe ,
0 commit comments