PERF: avoid N+1 on topic view

Serializer is injecting information into cooked and reaching direct to
custom fields that were not preloaded

This amends it so basic post serializer can use the proper interface

That said we should probably follow this up so we don't reach for this
info on every post.
This commit is contained in:
Sam Saffron 2019-08-19 17:20:56 +10:00
parent 10b36c6446
commit accbbded15
2 changed files with 30 additions and 22 deletions

View File

@ -10,6 +10,8 @@ class BasicPostSerializer < ApplicationSerializer
:cooked,
:cooked_hidden
attr_accessor :topic_view
def name
object.user && object.user.name
end
@ -41,20 +43,27 @@ class BasicPostSerializer < ApplicationSerializer
cooked = object.filter_quotes(@parent_post)
if scope&.user
group = Group
.joins('JOIN group_users ON groups.id = group_users.group_id')
.find_by(
id: object.custom_fields['requested_group_id'].to_i,
group_users: { user_id: scope.user.id, owner: true }
)
if group
cooked << <<~EOF
<hr />
<a href="#{Discourse.base_uri}/g/#{group.name}/requests">
#{I18n.t('groups.request_membership_pm.handle')}
</a>
EOF
# PERF: this should not run on every post, only specific ones
# also, why is this in basic post serializer?
requested_group_id = post_custom_fields['requested_group_id'].to_i
if requested_group_id > 0
group = Group
.joins('JOIN group_users ON groups.id = group_users.group_id')
.find_by(
id: object.custom_fields['requested_group_id'].to_i,
group_users: { user_id: scope.user.id, owner: true }
)
if group
cooked << <<~EOF
<hr />
<a href="#{Discourse.base_uri}/g/#{group.name}/requests">
#{I18n.t('groups.request_membership_pm.handle')}
</a>
EOF
end
end
end
@ -66,4 +75,12 @@ class BasicPostSerializer < ApplicationSerializer
SiteSetting.enable_names?
end
def post_custom_fields
@post_custom_fields ||= if @topic_view
(@topic_view.post_custom_fields || {})[object.id] || {}
else
object.custom_fields
end
end
end

View File

@ -4,7 +4,6 @@ class PostSerializer < BasicPostSerializer
# To pass in additional information we might need
INSTANCE_VARS ||= [
:topic_view,
:parent_post,
:add_raw,
:add_title,
@ -490,12 +489,4 @@ private
@post_actions ||= (@topic_view&.all_post_actions || {})[object.id]
end
def post_custom_fields
@post_custom_fields ||= if @topic_view
(@topic_view.post_custom_fields || {})[object.id] || {}
else
object.custom_fields
end
end
end