diff --git a/app/models/directory_item.rb b/app/models/directory_item.rb index 894545fbd9a..470275996ac 100644 --- a/app/models/directory_item.rb +++ b/app/models/directory_item.rb @@ -162,7 +162,11 @@ class DirectoryItem < ActiveRecord::Base #{Array.new(column_names.count, 0).join(", ")} FROM users u LEFT JOIN directory_items di ON di.user_id = u.id AND di.period_type = :period_type - WHERE di.id IS NULL AND u.id > 0 AND u.silenced_till IS NULL AND u.active + WHERE di.id IS NULL AND u.id > 0 AND u.silenced_till IS NULL AND u.active AND NOT EXISTS( + SELECT 1 + FROM anonymous_users + WHERE anonymous_users.user_id = u.id + ) #{SiteSetting.must_approve_users ? "AND u.approved" : ""} ", period_type: period_types[period_type], diff --git a/db/post_migrate/20240912210450_delete_anonymous_users_from_directory_items.rb b/db/post_migrate/20240912210450_delete_anonymous_users_from_directory_items.rb new file mode 100644 index 00000000000..bfebef1ba57 --- /dev/null +++ b/db/post_migrate/20240912210450_delete_anonymous_users_from_directory_items.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +class DeleteAnonymousUsersFromDirectoryItems < ActiveRecord::Migration[7.1] + def up + DB.exec(<<~SQL) + DELETE FROM directory_items + USING anonymous_users + WHERE directory_items.user_id = anonymous_users.user_id + SQL + end +end diff --git a/spec/models/directory_item_spec.rb b/spec/models/directory_item_spec.rb index e72b088d810..1fec2148687 100644 --- a/spec/models/directory_item_spec.rb +++ b/spec/models/directory_item_spec.rb @@ -182,5 +182,22 @@ RSpec.describe DirectoryItem do expect(DirectoryItem.where(user_id: user.id).count).to eq(0) end end + + context "with anonymous posting" do + fab!(:user) + fab!(:group) { Fabricate(:group, users: [user]) } + + before do + SiteSetting.allow_anonymous_posting = true + SiteSetting.anonymous_posting_allowed_groups = group.id.to_s + end + + it "doesn't create records for anonymous users" do + anon = AnonymousShadowCreator.get(user) + DirectoryItem.refresh! + expect(DirectoryItem.where(user_id: anon.id)).to be_blank + expect(DirectoryItem.where(user_id: user.id)).to be_present + end + end end end