PERF: Use UserAction to count accepted answers (#162)

The previous query which used custom fields performed a much more
complex and slower search.
This commit is contained in:
Bianca Nenciu 2021-09-13 19:26:43 +03:00 committed by GitHub
parent 2a774f0d6f
commit b558caff37
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 10 deletions

View File

@ -687,13 +687,14 @@ SQL
}
end
if defined?(UserAction::SOLVED)
add_to_serializer(:user_card, :accepted_answers) do
Post
UserAction
.where(user_id: object.id)
.joins(:_custom_fields)
.where(_custom_fields: { name: 'is_accepted_answer', value: 'true' })
.where(action_type: UserAction::SOLVED)
.count
end
end
if respond_to?(:register_topic_list_preload_user_ids)
class ::Topic

View File

@ -8,12 +8,15 @@ describe UserCardSerializer do
let(:json) { serializer.as_json }
it "accepted_answers serializes number of accepted answers" do
post = Fabricate(:post, user: user)
post.upsert_custom_fields(is_accepted_answer: 'true')
post1 = Fabricate(:post, user: user)
DiscourseSolved.accept_answer!(post1, Discourse.system_user)
expect(serializer.as_json[:accepted_answers]).to eq(1)
post = Fabricate(:post, user: user)
post.upsert_custom_fields(is_accepted_answer: 'true')
post2 = Fabricate(:post, user: user)
DiscourseSolved.accept_answer!(post2, Discourse.system_user)
expect(serializer.as_json[:accepted_answers]).to eq(2)
DiscourseSolved.unaccept_answer!(post1)
expect(serializer.as_json[:accepted_answers]).to eq(1)
end
end