Skip to content

Commit 572549b

Browse files
authored
DEV: Prevent N+1 on topic show and add index on post_locales for post_id (#314)
For privileged users in restrict_translation_by_group, we show the 🌐 per post. Showing the 🌐 depends on the post's locale. This commit ensures locale is preloaded to prevent N+1 and adds an index on post_locale for the post_id.
1 parent 998077a commit 572549b

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

app/models/discourse_translator/post_locale.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,7 @@ class PostLocale < ActiveRecord::Base
2121
# created_at :datetime not null
2222
# updated_at :datetime not null
2323
#
24+
# Indexes
25+
#
26+
# index_discourse_translator_post_locales_on_post_id (post_id) UNIQUE
27+
#
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# frozen_string_literal: true
2+
3+
class AddIndexPostLocalePostId < ActiveRecord::Migration[7.2]
4+
disable_ddl_transaction!
5+
6+
def up
7+
# clean up invalid index if index creation timeout
8+
execute <<~SQL
9+
DROP INDEX IF EXISTS index_discourse_translator_post_locales_on_post_id
10+
SQL
11+
12+
execute <<~SQL
13+
CREATE UNIQUE INDEX CONCURRENTLY index_discourse_translator_post_locales_on_post_id
14+
ON discourse_translator_post_locales (post_id)
15+
SQL
16+
end
17+
18+
def down
19+
raise ActiveRecord::IrreversibleMigration
20+
end
21+
end

plugin.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ module ::DiscourseTranslator
3131
Topic.prepend(DiscourseTranslator::Extensions::TopicExtension)
3232
end
3333

34+
TopicView.on_preload do |topic_view|
35+
topic_view.instance_variable_set(:@posts, topic_view.posts.includes(:content_locale))
36+
end
37+
3438
add_to_serializer :post, :can_translate do
3539
scope.can_translate?(object)
3640
end

0 commit comments

Comments
 (0)