mirror of
https://github.com/discourse/discourse.git
synced 2025-10-04 17:32:34 +08:00
DEV: Prevent N+1s when topic list (e.g. /latest) has localized titles (#33616)
Currently visible on <https://meta.discourse.org/tag/chinese-translation> for `Developers`, we see an N+1 when loading /latest or any other topic lists due to `topic_localizations.find_by` which will hit the db. This PR switches us to use `find` instead as the associations have been loaded already, and includes a test.
This commit is contained in:
parent
f1c7d5fd8e
commit
d814ef3fa4
2 changed files with 39 additions and 1 deletions
|
@ -2143,7 +2143,8 @@ class Topic < ActiveRecord::Base
|
|||
end
|
||||
|
||||
def get_localization(locale = I18n.locale)
|
||||
topic_localizations.find_by(locale: locale.to_s.sub("-", "_"))
|
||||
locale_string = locale.to_s.sub("-", "_")
|
||||
topic_localizations.find { |tl| tl.locale == locale_string }
|
||||
end
|
||||
|
||||
private
|
||||
|
|
|
@ -2371,4 +2371,41 @@ RSpec.describe TopicQuery do
|
|||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "content_localization enabled" do
|
||||
fab!(:user)
|
||||
fab!(:topics) { Fabricate.times(3, :topic) }
|
||||
fab!(:topic_localization1) do
|
||||
Fabricate(
|
||||
:topic_localization,
|
||||
topic: topics[0],
|
||||
locale: "fr",
|
||||
title: "Bonjour",
|
||||
fancy_title: "Bonjour",
|
||||
)
|
||||
end
|
||||
fab!(:topic_localization2) do
|
||||
Fabricate(
|
||||
:topic_localization,
|
||||
topic: topics[1],
|
||||
locale: "es",
|
||||
title: "Hola",
|
||||
fancy_title: "Hola",
|
||||
)
|
||||
end
|
||||
|
||||
before { SiteSetting.content_localization_enabled = true }
|
||||
|
||||
it "doesn't generate N+1 queries when accessing a localization's fancy_title" do
|
||||
topic_query = TopicQuery.new(user)
|
||||
topic_list = topic_query.list_latest
|
||||
|
||||
expect(topic_list.topics.first.association(:topic_localizations).loaded?).to eq(true)
|
||||
|
||||
queries =
|
||||
track_sql_queries { topic_list.topics.each { |topic| topic.get_localization&.fancy_title } }
|
||||
|
||||
expect(queries.select { |q| q.include?("topic_localizations") }).to be_empty
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue