Determine agent connections with cached COUNT queries

This commit is contained in:
Dominik Sander 2016-04-29 11:55:22 +02:00
parent 96537fcd3a
commit 506a70837f
4 changed files with 25 additions and 7 deletions

View file

@ -6,7 +6,7 @@ class AgentsController < ApplicationController
def index
set_table_sort sorts: %w[name created_at last_check_at last_event_at last_receive_at], default: { created_at: :desc }
@agents = current_user.agents.preload(:scenarios, :controllers, :links_as_receiver, :links_as_source, :control_links_as_controller).reorder(table_sort).page(params[:page])
@agents = current_user.agents.preload(:scenarios, :controllers).reorder(table_sort).page(params[:page])
if show_only_enabled_agents?
@agents = @agents.where(disabled: false)

View file

@ -26,7 +26,7 @@ class ScenariosController < ApplicationController
@scenario = current_user.scenarios.find(params[:id])
set_table_sort sorts: %w[name last_check_at last_event_at last_receive_at], default: { name: :asc }
@agents = @scenario.agents.preload(:scenarios, :controllers, :links_as_receiver, :links_as_source, :control_links_as_controller).reorder(table_sort).page(params[:page])
@agents = @scenario.agents.preload(:scenarios, :controllers).reorder(table_sort).page(params[:page])
respond_to do |format|
format.html

View file

@ -58,10 +58,10 @@ module AgentHelper
end
end
def agent_type_icon(agent)
receiver_count = agent.links_as_receiver.length
control_count = agent.control_links_as_controller.length
source_count = agent.links_as_source.length
def agent_type_icon(agent, agents)
receiver_count = links_counter_cache(agents)[:links_as_receiver][agent.id] || 0
control_count = links_counter_cache(agents)[:control_links_as_controller][agent.id] || 0
source_count = links_counter_cache(agents)[:links_as_source][agent.id] || 0
if control_count > 0 && receiver_count > 0
content_tag('span') do
@ -81,4 +81,22 @@ module AgentHelper
icon_tag('glyphicon-unchecked')
end
end
private
def links_counter_cache(agents)
@counter_cache ||= {}
@counter_cache[agents.__id__] ||= {}.tap do |cache|
agent_ids = agents.map(&:id)
cache[:links_as_receiver] = Hash[Link.where(receiver_id: agent_ids)
.group(:receiver_id)
.pluck('receiver_id', 'count(receiver_id) as id')]
cache[:links_as_source] = Hash[Link.where(source_id: agent_ids)
.group(:source_id)
.pluck('source_id', 'count(source_id) as id')]
cache[:control_links_as_controller] = Hash[ControlLink.where(controller_id: agent_ids)
.group(:controller_id)
.pluck('controller_id', 'count(controller_id) as id')]
end
end
end

View file

@ -16,7 +16,7 @@
<% @agents.each do |agent| %>
<tr>
<td class='<%= "agent-unavailable" if agent.unavailable? %>'>
<%= agent_type_icon(agent) %>
<%= agent_type_icon(agent, @agents) %>
</td>
<td class='<%= "agent-unavailable" if agent.unavailable? %>'>
<%= link_to agent.name, agent_path(agent, return: (defined?(return_to) && return_to) || request.path) %>