From 821e9cb649f2910d465cd1ff925180fd02244c88 Mon Sep 17 00:00:00 2001 From: Joffrey JAFFEUX Date: Wed, 7 Jun 2023 13:30:38 +0200 Subject: [PATCH] PERF: avoids eager pluck in posts controller (#21973) Calling pluck is instantly making a SELECT, while passing the relationship allows rails to build a correct query. Before (2 selects): ``` pry(main)> Post.where(topic_id: Topic.where(id: [1,3,4]).pluck(:id)).count (1.3ms) SELECT "topics"."id" FROM "topics" WHERE "topics"."deleted_at" IS NULL AND "topics"."id" IN (1, 3, 4) Post Count (0.5ms) SELECT COUNT(*) FROM "posts" WHERE "posts"."deleted_at" IS NULL AND "posts"."topic_id" IN (1, 3, 4) ``` After (1 select): ``` pry(main)> Post.where(topic_id: Topic.where(id: [1,3,4])).count Post Count (2.7ms) SELECT COUNT(*) FROM "posts" WHERE "posts"."deleted_at" IS NULL AND "posts"."topic_id" IN (SELECT "topics"."id" FROM "topics" WHERE "topics"."deleted_at" IS NULL AND "topics"."id" IN (1, 3, 4)) ``` --- app/controllers/posts_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 078b0efc9e0..42a819c3785 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -783,7 +783,7 @@ class PostsController < ApplicationController topics = Topic.where(id: topic_ids).with_deleted.where.not(archetype: "private_message") topics = topics.secured(guardian) - posts = posts.where(topic_id: topics.pluck(:id)) + posts = posts.where(topic_id: topics) end posts.offset(opts[:offset]).limit(opts[:limit])