From 5db8cb452e0e2d86faea94e53bc1f534f5de4d5f Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Thu, 19 Dec 2024 09:47:43 +1100 Subject: [PATCH] Leverage Rails' caching when checking for admin The privileges of a user should never change within a request life cycle. The `spree_roles` association is very small, between 0 and 2 items are quickly searched in memory without the need of additional database queries. From memory, I've seen a lot of spree_roles queries in log files per request. This should reduce it to one. --- app/models/spree/user.rb | 2 +- spec/controllers/admin/order_cycles_controller_spec.rb | 1 - spec/lib/reports/orders_and_distributors_report_spec.rb | 2 -- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/app/models/spree/user.rb b/app/models/spree/user.rb index 392f5fd5e1..371ab636f7 100644 --- a/app/models/spree/user.rb +++ b/app/models/spree/user.rb @@ -60,7 +60,7 @@ module Spree # Checks whether the specified user is a superadmin, with full control of the instance def admin? - spree_roles.where(name: "admin").any? + spree_roles.any? { |role| role.name == "admin" } end # Send devise-based user emails asyncronously via ActiveJob diff --git a/spec/controllers/admin/order_cycles_controller_spec.rb b/spec/controllers/admin/order_cycles_controller_spec.rb index 6f02b81802..b91bf12377 100644 --- a/spec/controllers/admin/order_cycles_controller_spec.rb +++ b/spec/controllers/admin/order_cycles_controller_spec.rb @@ -148,7 +148,6 @@ module Admin order_cycles: 6, proxy_orders: 1, schedules: 1, - spree_roles: 9, spree_variants: 8, tags: 1 }, diff --git a/spec/lib/reports/orders_and_distributors_report_spec.rb b/spec/lib/reports/orders_and_distributors_report_spec.rb index ba851aaf73..fa771cb86e 100644 --- a/spec/lib/reports/orders_and_distributors_report_spec.rb +++ b/spec/lib/reports/orders_and_distributors_report_spec.rb @@ -140,8 +140,6 @@ RSpec.describe Reporting::Reports::OrdersAndDistributors::Base do subject # build context first expect { subject.table_rows }.to query_database [ - "Spree::Role Exists?", - "Spree::Role Exists?", "SQL", "Spree::LineItem Load", "Spree::PaymentMethod Load",