Announcement reactions query spec improvement and refactor (#28768)
This commit is contained in:
parent
afb5e6cf46
commit
1b0cb3b54d
2 changed files with 46 additions and 18 deletions
|
@ -75,22 +75,41 @@ class Announcement < ApplicationRecord
|
|||
end
|
||||
|
||||
def reactions(account = nil)
|
||||
records = begin
|
||||
scope = announcement_reactions.group(:announcement_id, :name, :custom_emoji_id).order(Arel.sql('MIN(created_at) ASC'))
|
||||
|
||||
if account.nil?
|
||||
scope.select('name, custom_emoji_id, count(*) as count, false as me')
|
||||
else
|
||||
scope.select("name, custom_emoji_id, count(*) as count, exists(select 1 from announcement_reactions r where r.account_id = #{account.id} and r.announcement_id = announcement_reactions.announcement_id and r.name = announcement_reactions.name) as me")
|
||||
grouped_ordered_announcement_reactions.select(
|
||||
[:name, :custom_emoji_id, 'COUNT(*) as count'].tap do |values|
|
||||
values << value_for_reaction_me_column(account)
|
||||
end
|
||||
end.to_a
|
||||
|
||||
ActiveRecord::Associations::Preloader.new(records: records, associations: :custom_emoji).call
|
||||
records
|
||||
).to_a.tap do |records|
|
||||
ActiveRecord::Associations::Preloader.new(records: records, associations: :custom_emoji).call
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def grouped_ordered_announcement_reactions
|
||||
announcement_reactions
|
||||
.group(:announcement_id, :name, :custom_emoji_id)
|
||||
.order(
|
||||
Arel.sql('MIN(created_at)').asc
|
||||
)
|
||||
end
|
||||
|
||||
def value_for_reaction_me_column(account)
|
||||
if account.nil?
|
||||
'FALSE AS me'
|
||||
else
|
||||
<<~SQL.squish
|
||||
EXISTS(
|
||||
SELECT 1
|
||||
FROM announcement_reactions inner_reactions
|
||||
WHERE inner_reactions.account_id = #{account.id}
|
||||
AND inner_reactions.announcement_id = announcement_reactions.announcement_id
|
||||
AND inner_reactions.name = announcement_reactions.name
|
||||
) AS me
|
||||
SQL
|
||||
end
|
||||
end
|
||||
|
||||
def set_published
|
||||
return unless scheduled_at.blank? || scheduled_at.past?
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue