perf: AssignableAgentsController#index 中的严重 N+1 查询循环 (每次请求 100 多次查询)
作者: md-riaz创建于 2026年9月29日更新于 2026年9月29日
- In
app/controllers/api/v1/accounts/assignable_agents_controller.rb:
def index
@include_ai_assignees = params[:include_ai_assignees].present?
agent_ids = @inboxes.map do |inbox|
authorize inbox, :show?
inbox.members.pluck(:user_id)
end
agent_ids = agent_ids.inject(:&)
all_agent_ids = (agent_ids.to_a + Current.account.administrators.pluck(:id)).uniq
@assignable_agents = Current.account.users
.where(id: all_agent_ids)
@agent_bots = @include_ai_assignees ? AgentBot.accessible_to(Current.account) : []
end- In
app/views/api/v1/accounts/assignable_agents/index.json.jbuilder:
json.payload do
json.array! @assignable_agents do |agent|
json.partial! 'api/v1/models/agent', formats: [:json], resource: agent
end
end- In
app/views/api/v1/models/_agent.json.jbuilder: The view renders attributes like:
resource.availability_status(callscurrent_account_user)resource.auto_offline(callscurrent_account_user)resource.role(callscurrent_account_user)resource.thumbnail(callsresource.avatar_url->avatar_attachment-> ActiveStorage blob)resource.custom_role_id(callscurrent_account_user&.custom_role_id)
- In
app/models/concerns/user_attribute_helpers.rb:
def current_account_user
# We want to avoid subsequent queries in case where the association is preloaded.
# using where here will trigger n+1 queries.
account_users.find { |ac_usr| ac_usr.account_id == Current.account.id } if Current.account
endNote that the comment explicitly highlights that account_users must be preloaded. However, in AssignableAgentsController, neither account_users nor avatar_attachment: :blob are preloaded.
Observed Production Impact
In a production account with 47 agents:
- Executing
GET /api/v1/accounts/1/assignable_agents?inbox_ids[]=7&include_ai_assignees=truelogs:
Completed 200 OK in 821ms (Views: 393.8ms | ActiveRecord: 237.7ms (108 queries, 3 cached))Under concurrent dashboard loads, running 108 queries for a single dropdown list serializes behind Puma thread pools and causes response times to spike beyond 10-15 seconds.
内容来源: chatwoot/chatwoot