From 0d446ef015ddec29fcaddbd65a5db169a42cfd53 Mon Sep 17 00:00:00 2001 From: Iain McNulty Date: Fri, 25 Oct 2024 16:54:01 +0100 Subject: [PATCH] Reduce number of queries in the courses api --- app/models/course.rb | 2 ++ app/models/required_qualifications_summary.rb | 7 ++++++- app/serializers/api/public/v1/serializable_course.rb | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/models/course.rb b/app/models/course.rb index c3894c5035..105803454d 100644 --- a/app/models/course.rb +++ b/app/models/course.rb @@ -585,6 +585,8 @@ def gcse_grade_required end def last_published_at + return enrichments.max_by(&:last_published_timestamp_utc).last_published_timestamp_utc if enrichments.loaded? + enrichments.maximum(:last_published_timestamp_utc) end diff --git a/app/models/required_qualifications_summary.rb b/app/models/required_qualifications_summary.rb index ed68511a53..1031d88829 100644 --- a/app/models/required_qualifications_summary.rb +++ b/app/models/required_qualifications_summary.rb @@ -8,7 +8,12 @@ def initialize(course) end def extract - legacy_qualifications_attribute = course.latest_published_enrichment&.required_qualifications + # This performance improvement saves ~100 database queries in the courses api endpoint + legacy_qualifications_attribute = if course.enrichments.loaded? + course.enrichments.max_by(&:created_at)&.required_qualifications + else + course.latest_published_enrichment&.required_qualifications + end return legacy_qualifications_attribute if legacy_qualifications_attribute.present? generate_summary_text diff --git a/app/serializers/api/public/v1/serializable_course.rb b/app/serializers/api/public/v1/serializable_course.rb index d0d0b64956..8b0e7d2484 100644 --- a/app/serializers/api/public/v1/serializable_course.rb +++ b/app/serializers/api/public/v1/serializable_course.rb @@ -11,7 +11,7 @@ class SerializableCourse < JSONAPI::Serializable::Resource class << self def enrichment_attribute(name, enrichment_name = name) attribute name do - @object.latest_published_enrichment&.public_send(enrichment_name) + @object.enrichments.max_by(&:created_at)&.public_send(enrichment_name) end end end