From 5177aef37d87ea694053ecd9ddea41b471184dd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Guitaut?= Date: Tue, 22 Oct 2024 15:29:07 +0200 Subject: [PATCH] =?UTF-8?q?FIX:=20Don=E2=80=99t=20try=20to=20serialize=20a?= =?UTF-8?q?ssociations=20in=20`PostRevisionSerializer`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently, if an association is added as a tracked field in `PostRevisor`, the `PostRevisionSerializer` class will try to serialize it somehow. This will raise an error as ActiveRecord collection proxies can't be serialized. This patch addresses this issue by skipping any association tracked by the `PostRevisor` class. --- app/serializers/post_revision_serializer.rb | 9 +++++++-- .../serializers/post_revision_serializer_spec.rb | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/serializers/post_revision_serializer.rb b/app/serializers/post_revision_serializer.rb index 5a6939dfa49..5c59e82d9b9 100644 --- a/app/serializers/post_revision_serializer.rb +++ b/app/serializers/post_revision_serializer.rb @@ -219,8 +219,13 @@ class PostRevisionSerializer < ApplicationSerializer # Retrieve any `tracked_topic_fields` PostRevisor.tracked_topic_fields.each_key do |field| - next if field == :tags - latest_modifications[field.to_s] = [topic.public_send(field)] if topic.respond_to?(field) + next unless topic.respond_to?(field) + topic + .public_send(field) + .then do |value| + next if value.try(:proxy_association) + latest_modifications[field.to_s] = [value] + end end latest_modifications["featured_link"] = [ diff --git a/spec/serializers/post_revision_serializer_spec.rb b/spec/serializers/post_revision_serializer_spec.rb index bea000255f5..c70cf7f2a22 100644 --- a/spec/serializers/post_revision_serializer_spec.rb +++ b/spec/serializers/post_revision_serializer_spec.rb @@ -127,4 +127,20 @@ RSpec.describe PostRevisionSerializer do expect(json[:tags_changes]).to_not be_present end end + + context "when some tracked topic fields are associations" do + let(:serializer) { described_class.new(post_revision, scope: guardian, root: false) } + let(:post_revision) { Fabricate(:post_revision, post:) } + let(:guardian) { Discourse.system_user.guardian } + + before do + allow(PostRevisor).to receive(:tracked_topic_fields).and_wrap_original do |original_method| + original_method.call.merge(allowed_users: -> {}, allowed_groups: -> {}) + end + end + + it "skips them" do + expect { serializer.as_json }.not_to raise_error + end + end end