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:
parent
11d7270e36
commit
821e9cb649
|
@ -783,7 +783,7 @@ class PostsController < ApplicationController
|
||||||
topics = Topic.where(id: topic_ids).with_deleted.where.not(archetype: "private_message")
|
topics = Topic.where(id: topic_ids).with_deleted.where.not(archetype: "private_message")
|
||||||
topics = topics.secured(guardian)
|
topics = topics.secured(guardian)
|
||||||
|
|
||||||
posts = posts.where(topic_id: topics.pluck(:id))
|
posts = posts.where(topic_id: topics)
|
||||||
end
|
end
|
||||||
|
|
||||||
posts.offset(opts[:offset]).limit(opts[:limit])
|
posts.offset(opts[:offset]).limit(opts[:limit])
|
||||||
|
|
Loading…
Reference in New Issue