diff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rb index b7489167f4d..c91ebef82cd 100644 --- a/app/serializers/current_user_serializer.rb +++ b/app/serializers/current_user_serializer.rb @@ -135,7 +135,7 @@ class CurrentUserSerializer < BasicUserSerializer end if fields.present? - User.custom_fields_for_ids([object.id], fields)[object.id] + User.custom_fields_for_ids([object.id], fields)[object.id] || {} else {} end diff --git a/app/serializers/user_serializer.rb b/app/serializers/user_serializer.rb index 895a7a39a5a..b81bbcbe7fc 100644 --- a/app/serializers/user_serializer.rb +++ b/app/serializers/user_serializer.rb @@ -388,7 +388,7 @@ class UserSerializer < BasicUserSerializer end if fields.present? - User.custom_fields_for_ids([object.id], fields)[object.id] + User.custom_fields_for_ids([object.id], fields)[object.id] || {} else {} end diff --git a/spec/components/plugin/instance_spec.rb b/spec/components/plugin/instance_spec.rb index 942647b85b5..35a770db519 100644 --- a/spec/components/plugin/instance_spec.rb +++ b/spec/components/plugin/instance_spec.rb @@ -149,6 +149,14 @@ describe Plugin::Instance do end context "serialized_current_user_fields" do + before do + DiscoursePluginRegistry.serialized_current_user_fields << "has_car" + end + + after do + DiscoursePluginRegistry.serialized_current_user_fields.delete "has_car" + end + it "correctly serializes custom user fields" do DiscoursePluginRegistry.serialized_current_user_fields << "has_car" user = Fabricate(:user) @@ -157,6 +165,18 @@ describe Plugin::Instance do payload = JSON.parse(CurrentUserSerializer.new(user, scope: Guardian.new(user)).to_json) expect(payload["current_user"]["custom_fields"]["has_car"]).to eq("true") + + payload = JSON.parse(UserSerializer.new(user, scope: Guardian.new(user)).to_json) + expect(payload["user"]["custom_fields"]["has_car"]).to eq("true") + + UserCustomField.destroy_all + user.reload + + payload = JSON.parse(CurrentUserSerializer.new(user, scope: Guardian.new(user)).to_json) + expect(payload["current_user"]["custom_fields"]).to eq({}) + + payload = JSON.parse(UserSerializer.new(user, scope: Guardian.new(user)).to_json) + expect(payload["user"]["custom_fields"]).to eq({}) end end