A platform for community discussion. Free, open, simple.
DEV: Allow additional TopicList preloaded associations (#18891)
jbrw1a48ea767e95
diff --git a/app/models/topic_list.rb b/app/models/topic_list.rbindex d13c2ab3ecd..815e9c23085 100644--- a/app/models/topic_list.rb+++ b/app/models/topic_list.rb@@ -136,8 +136,11 @@ class TopicListft.topic_list = selfend+ topic_preloader_associations = [:image_upload, { topic_thumbnails: :optimized_image }]+ topic_preloader_associations.concat(DiscoursePluginRegistry.topic_preloader_associations.to_a)+ActiveRecord::Associations::Preloader- .new(records: @topics, associations: [:image_upload, topic_thumbnails: :optimized_image])+ .new(records: @topics, associations: topic_preloader_associations).callif preloaded_custom_fields.present?diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rbindex c9d0baf5915..7272b4f0b76 100644--- a/lib/discourse_plugin_registry.rb+++ b/lib/discourse_plugin_registry.rb@@ -80,6 +80,7 @@ class DiscoursePluginRegistrydefine_filtered_register :group_paramsdefine_filtered_register :topic_thumbnail_sizes+ define_filtered_register :topic_preloader_associationsdefine_filtered_register :api_parameter_routesdefine_filtered_register :api_key_scope_mappingsdiff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex 09ceac7804e..579c9ffd894 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -1220,6 +1220,10 @@ class Plugin::Instanceendend+ def register_topic_preloader_associations(fields)+ DiscoursePluginRegistry.register_topic_preloader_association(fields, self)+ end+privatedef validate_directory_column_name(column_name)diff --git a/spec/lib/topic_query_spec.rb b/spec/lib/topic_query_spec.rbindex e09227b7120..3b689982f5d 100644--- a/spec/lib/topic_query_spec.rb+++ b/spec/lib/topic_query_spec.rb@@ -919,6 +919,22 @@ RSpec.describe TopicQuery doendend+ context 'when preloading associations' do+ it "preloads associations" do+ DiscoursePluginRegistry.register_topic_preloader_association(:first_post, Plugin::Instance.new)++ topic = Fabricate(:topic)+ Fabricate(:post, topic: topic)++ new_topic = topic_query.list_new.topics.first+ expect(new_topic.association(:image_upload).loaded?).to eq(true) # Preloaded by default+ expect(new_topic.association(:first_post).loaded?).to eq(true) # Testing a user-defined preloaded association+ expect(new_topic.association(:user).loaded?).to eq(false) # Testing the negative++ DiscoursePluginRegistry.reset_register!(:topic_preloader_associations)+ end+ end+context 'with a new topic' dolet!(:new_topic) { Fabricate(:topic, user: creator, bumped_at: 10.minutes.ago) }let(:topics) { topic_query.list_new.topics }