<%
  categories = Category
    .active_batch_scope
    .joins(:packages)
    .merge(Package.exclude_unregistered_packages(cookies))
    .group("categories.id")
    .order("count(categories.id) desc")
%>

<% categories.each_with_index do |category, index| %>

  <% unless index.zero? %>

    <div class="list-group-separator cs-full-width cs-no-margin"></div>

  <% end %>

  <div class="list-group-item cs-no-padding" id="js-sidebar-categories__<%= category.name.gsub(' ', '-').underscore.dasherize %>">

    <div class="row-content cs-full-width cs-category-row">

      <%=
        link_to category.name,
          category_path(category),
          class: "btn btn-default cs-full-width cs-left-align cs-no-margin #{ 'active' if current_page?(category_path(category)) }"
      %>

    </div>

  </div>

<% end %>

<%
  categories = Category
    .active_batch_scope
    .joins(:packages)
    .merge(Package.exclude_unregistered_packages(cookies))
    .references(:packages)
    .group("categories.id")
    .order("count(categories.id) desc")
%>

<% categories.each_with_index do |category, index| %>

  <% unless index.zero? %>

    <div class="list-group-separator cs-full-width cs-no-margin"></div>

  <% end %>

  <div class="list-group-item cs-no-padding" id="js-sidebar-categories__<%= category.name.gsub(' ', '-').underscore.dasherize %>">

    <div class="row-content cs-full-width cs-category-row">

      <%=
        link_to category.name,
          category_path(category),
          class: "btn btn-default cs-full-width cs-left-align cs-no-margin #{ 'active' if current_page?(category_path(category)) }"
      %>

    </div>

  </div>

<% end %>

Enforce references on category sidebar query
Enforce references on category sidebar query