gitlab-org--gitlab-foss/app/controllers/concerns/group_tree.rb
Bob Van Landuyt de35c044fb Preload ancestors after pagination when filtering
We need to preload the ancestors of search results after applying
pagination limits. This way the search results itself are paginated,
but not the ancestors.

If we don't do this, we might not preload a parent group of a search
result as it has been cut off by pagination.
2018-07-06 14:09:36 +02:00

43 lines
1.5 KiB
Ruby

module GroupTree
# rubocop:disable Gitlab/ModuleWithInstanceVariables
def render_group_tree(groups)
groups = groups.sort_by_attribute(@sort = params[:sort])
groups = if params[:filter].present?
filtered_groups_with_ancestors(groups)
else
# If `params[:parent_id]` is `nil`, we will only show root-groups
groups.where(parent_id: params[:parent_id]).page(params[:page])
end
@groups = groups.with_selects_for_list(archived: params[:archived])
respond_to do |format|
format.html
format.json do
serializer = GroupChildSerializer.new(current_user: current_user)
.with_pagination(request, response)
serializer.expand_hierarchy if params[:filter].present?
render json: serializer.represent(@groups)
end
end
# rubocop:enable Gitlab/ModuleWithInstanceVariables
end
def filtered_groups_with_ancestors(groups)
filtered_groups = groups.search(params[:filter]).page(params[:page])
if Group.supports_nested_groups?
# We find the ancestors by ID of the search results here.
# Otherwise the ancestors would also have filters applied,
# which would cause them not to be preloaded.
#
# Pagination needs to be applied before loading the ancestors to
# make sure ancestors are not cut off by pagination.
Gitlab::GroupHierarchy.new(Group.where(id: filtered_groups.select(:id)))
.base_and_ancestors
else
filtered_groups
end
end
end