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))
```
This commit is contained in:
Joffrey JAFFEUX 2023-06-07 13:30:38 +02:00 committed by GitHub
parent 11d7270e36
commit 821e9cb649
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 1 additions and 1 deletions

View File

@ -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])