From 20127398c643dd6f8a5ed2a3e6759b3a2f7d8e41 Mon Sep 17 00:00:00 2001 From: Manuel Bustillo Date: Sun, 8 Dec 2024 11:39:50 +0100 Subject: [PATCH] Fix summary query to leverage ActsAsTenant scopes --- Gemfile | 1 + Gemfile.lock | 4 ++++ app/queries/groups/summary_query.rb | 36 +++++++++++------------------ 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/Gemfile b/Gemfile index e7c867a..0a618dd 100644 --- a/Gemfile +++ b/Gemfile @@ -23,6 +23,7 @@ gem 'rubytree' gem 'acts_as_tenant' gem 'httparty' gem 'rswag' +gem 'pluck_to_hash' group :development, :test do gem 'annotaterb' diff --git a/Gemfile.lock b/Gemfile.lock index dde22ed..854d1cd 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -222,6 +222,9 @@ GEM ast (~> 2.4.1) racc pg (1.5.9) + pluck_to_hash (1.0.2) + activerecord (>= 4.0.2) + activesupport (>= 4.0.2) pry (0.15.0) coderay (~> 1.1) method_source (~> 1.0) @@ -413,6 +416,7 @@ DEPENDENCIES license_finder money pg (~> 1.1) + pluck_to_hash pry puma (>= 5.0) rack-cors diff --git a/app/queries/groups/summary_query.rb b/app/queries/groups/summary_query.rb index 70fc234..0736496 100644 --- a/app/queries/groups/summary_query.rb +++ b/app/queries/groups/summary_query.rb @@ -3,29 +3,19 @@ module Groups class SummaryQuery def call - ActiveRecord::Base.connection.execute(query).to_a - end - - private - - def query - <<~SQL.squish - SELECT - groups.id, - groups.name, - groups.icon, - groups.parent_id, - groups.color, - count(*) filter (where status IS NOT NULL) as total, - count(*) filter (where status = 0) as considered, - count(*) filter (where status = 10) as invited, - count(*) filter (where status = 20) as confirmed, - count(*) filter (where status = 30) as declined, - count(*) filter (where status = 40) as tentative - FROM groups - LEFT JOIN guests on groups.id = guests.group_id - GROUP BY groups.id - SQL + Group.left_joins(:guests).group(:id).pluck_to_hash( + :id, + :name, + :icon, + :parent_id, + :color, + Arel.sql('count(*) filter (where status IS NOT NULL) as total'), + Arel.sql('count(*) filter (where status = 0) as considered'), + Arel.sql('count(*) filter (where status = 10) as invited'), + Arel.sql('count(*) filter (where status = 20) as confirmed'), + Arel.sql('count(*) filter (where status = 30) as declined'), + Arel.sql('count(*) filter (where status = 40) as tentative'), + ) end end end