From e0713455cabb2c155261052935dbe35e00b0539f Mon Sep 17 00:00:00 2001 From: Martin Brennan Date: Thu, 9 Jul 2020 15:46:52 +1000 Subject: [PATCH] PERF: Load topic bookmarks for the user in user_post_bookmarks (#10197) Instead of loading all of the user bookmarks using all the post IDs in a topic, load all the bookmarks for a user using the topic ID. This eliminates a costly WHERE ID IN query. --- lib/topic_view.rb | 2 +- spec/components/topic_view_spec.rb | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/topic_view.rb b/lib/topic_view.rb index bea37c15e89..aa0c46aa1a9 100644 --- a/lib/topic_view.rb +++ b/lib/topic_view.rb @@ -435,7 +435,7 @@ class TopicView end def user_post_bookmarks - @user_post_bookmarks ||= Bookmark.where(user: @user, post_id: unfiltered_post_ids) + @user_post_bookmarks ||= @topic.bookmarks.where(user: @user) end def reviewable_counts diff --git a/spec/components/topic_view_spec.rb b/spec/components/topic_view_spec.rb index 31dcd75481c..624e9a3b4a1 100644 --- a/spec/components/topic_view_spec.rb +++ b/spec/components/topic_view_spec.rb @@ -334,6 +334,19 @@ describe TopicView do end end + context "#user_post_bookmarks" do + let!(:user) { Fabricate(:user) } + let!(:bookmark1) { Fabricate(:bookmark, post: Fabricate(:post, topic: topic), user: user) } + let!(:bookmark2) { Fabricate(:bookmark, post: Fabricate(:post, topic: topic), user: user) } + let!(:bookmark3) { Fabricate(:bookmark, post: Fabricate(:post, topic: topic)) } + + it "returns all the bookmarks in the topic for a user" do + expect(TopicView.new(topic.id, user).user_post_bookmarks.pluck(:id)).to match_array( + [bookmark1.id, bookmark2.id] + ) + end + end + context '.topic_user' do it 'returns nil when there is no user' do expect(TopicView.new(topic.id, nil).topic_user).to be_blank