PERF: Make `TopicViewSerializer#requested_group_name` more efficient. (#14196)
* Avoid executing a query when the custom field doesn't exist * Avoid generating an ActiveRecord when all we need is the name.
This commit is contained in:
parent
7a604215e0
commit
c2f87e0a36
|
@ -260,20 +260,17 @@ class TopicViewSerializer < ApplicationSerializer
|
|||
end
|
||||
|
||||
def requested_group_name
|
||||
if scope&.user
|
||||
group = Group
|
||||
.joins('JOIN group_users ON groups.id = group_users.group_id')
|
||||
.find_by(
|
||||
id: object.topic.custom_fields['requested_group_id'].to_i,
|
||||
group_users: { user_id: scope.user.id, owner: true }
|
||||
)
|
||||
|
||||
group.name if group
|
||||
end
|
||||
Group
|
||||
.joins(:group_users)
|
||||
.where(
|
||||
id: object.topic.custom_fields['requested_group_id'].to_i,
|
||||
group_users: { user_id: scope.user.id, owner: true }
|
||||
)
|
||||
.pluck_first(:name)
|
||||
end
|
||||
|
||||
def include_requested_group_name?
|
||||
object.personal_message
|
||||
object.personal_message && object.topic.custom_fields['requested_group_id']
|
||||
end
|
||||
|
||||
def include_published_page?
|
||||
|
|
|
@ -484,4 +484,26 @@ describe TopicViewSerializer do
|
|||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#requested_group_name' do
|
||||
fab!(:pm) { Fabricate(:private_message_post).topic }
|
||||
fab!(:group) { Fabricate(:group) }
|
||||
|
||||
it 'should return the right group name when PM is a group membership request' do
|
||||
pm.custom_fields[:requested_group_id] = group.id
|
||||
pm.save!
|
||||
|
||||
user = pm.first_post.user
|
||||
group.add_owner(user)
|
||||
json = serialize_topic(pm, user)
|
||||
|
||||
expect(json[:requested_group_name]).to eq(group.name)
|
||||
end
|
||||
|
||||
it 'should not include the attribute for a non group membership request PM' do
|
||||
json = serialize_topic(pm, pm.first_post.user)
|
||||
|
||||
expect(json[:requested_group_name]).to eq(nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue