Only preload accounts in Collections when needed (#39143)
This commit is contained in:
parent
ae8b794c66
commit
dee85c6df9
@ -64,11 +64,15 @@ class Collection < ApplicationRecord
|
||||
!local?
|
||||
end
|
||||
|
||||
def items_for(account = nil)
|
||||
result = collection_items.with_accounts
|
||||
result = account == self.account ? result.pending_or_accepted : result.accepted
|
||||
result = result.not_blocked_by(account) unless account.nil?
|
||||
result
|
||||
def items_for(account = nil, include_accounts: false)
|
||||
@items_for ||= {}
|
||||
@items_for[account] ||= begin
|
||||
result = collection_items
|
||||
result = result.with_accounts if include_accounts
|
||||
result = account == self.account ? result.pending_or_accepted : result.accepted
|
||||
result = result.not_blocked_by(account) unless account.nil?
|
||||
result
|
||||
end
|
||||
end
|
||||
|
||||
def tag_name
|
||||
|
||||
@ -43,7 +43,7 @@ class CollectionItem < ApplicationRecord
|
||||
|
||||
scope :ordered, -> { order(position: :asc) }
|
||||
scope :with_accounts, -> { includes(account: [:account_stat, :user]) }
|
||||
scope :not_blocked_by, ->(account) { where.not(accounts: { id: account.blocking }) }
|
||||
scope :not_blocked_by, ->(account) { joins(:account).where.not(accounts: { id: account.blocking }) }
|
||||
scope :local, -> { joins(:collection).merge(Collection.local) }
|
||||
scope :accepted_partial, ->(account) { joins(:account).merge(Account.local).accepted.where(uri: nil, account_id: account.id) }
|
||||
scope :pending_or_accepted, -> { where(state: [:pending, :accepted]) }
|
||||
|
||||
@ -10,6 +10,6 @@ class REST::CollectionWithAccountsSerializer < ActiveModel::Serializer
|
||||
end
|
||||
|
||||
def accounts
|
||||
[object.account] + object.collection_items.filter_map(&:account)
|
||||
[object.account] + object.items_for(current_user&.account, include_accounts: true).map(&:account)
|
||||
end
|
||||
end
|
||||
|
||||
@ -124,6 +124,28 @@ RSpec.describe Collection do
|
||||
expect(subject.items_for(account)).to match_array(accepted_items + [pending_item])
|
||||
end
|
||||
end
|
||||
|
||||
context 'when `include_accounts` is set to `true`' do
|
||||
it 'preloads accounts' do
|
||||
items = subject.items_for(include_accounts: true).to_a
|
||||
|
||||
expect { items.first.account }.to_not execute_queries
|
||||
end
|
||||
end
|
||||
|
||||
context 'when called multiple times' do
|
||||
let(:account) { subject.account }
|
||||
|
||||
it 'memoizes results' do
|
||||
subject.items_for.to_a
|
||||
|
||||
expect { subject.items_for.to_a }.to_not execute_queries
|
||||
|
||||
expect { subject.items_for(account).to_a }.to execute_queries
|
||||
|
||||
expect { subject.items_for(account).to_a }.to_not execute_queries
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe '#tag_name=' do
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user