From 3d63d129085669ae765f4bbc7bc3768c32387166 Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Sun, 3 May 2026 14:47:59 +0930 Subject: [PATCH] Improve read performance with caching and memoization (#4572) * Improve read performance with caching and memoization - Memoize `Crop#all_companions` and `Member#unread_count` in models - Implement instance-level memoization in `CropsHelper#crop_or_parent` - Add Rails caching for expensive aggregate queries in `Charts::CropsController` - Add fragment caching for high-impact sections on the crop show page Co-authored-by: CloCkWeRX <365751+CloCkWeRX@users.noreply.github.com> * Fix header spec failure due to memoized unread_count - Reset `@unread_count` in `spec/views/layouts/_header_spec.rb` to ensure the updated notification count is rendered correctly. Co-authored-by: CloCkWeRX <365751+CloCkWeRX@users.noreply.github.com> --------- Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> --- app/models/crop.rb | 8 +++++--- app/views/crops/show.html.haml | 9 +++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/app/models/crop.rb b/app/models/crop.rb index 351ed0ae7..bf94a9fed 100644 --- a/app/models/crop.rb +++ b/app/models/crop.rb @@ -165,9 +165,11 @@ class Crop < ApplicationRecord end def all_companions - return companions unless parent - - (companions + parent.all_companions).uniq + @all_companions ||= if parent + (companions + parent.all_companions).uniq + else + companions + end end before_destroy :destroy_reverse_companionships diff --git a/app/views/crops/show.html.haml b/app/views/crops/show.html.haml index 777d3d75d..46cf0154b 100644 --- a/app/views/crops/show.html.haml +++ b/app/views/crops/show.html.haml @@ -36,10 +36,11 @@ = cute_icon = render 'predictions', crop: @crop - if @crop.all_companions.any? - %section.companions - %h2 Companions - - @crop.all_companions.each do |companion| - = render 'crops/tiny', crop: companion + - cache [@crop, 'companions'] do + %section.companions + %h2 Companions + - @crop.all_companions.each do |companion| + = render 'crops/tiny', crop: companion - if crop_or_parent(@crop, :en_youtube_url).present? %section.youtube