diff --git a/app/models/category_list.rb b/app/models/category_list.rb index 0e5828b3daf..1d08a9a6d9e 100644 --- a/app/models/category_list.rb +++ b/app/models/category_list.rb @@ -142,13 +142,17 @@ class CategoryList query = self.class.order_categories(query) + page = [1, @options[:page].to_i].max if @guardian.can_lazy_load_categories? && @options[:parent_category_id].blank? - page = [1, @options[:page].to_i].max query = query .where(parent_category_id: nil) .limit(CATEGORIES_PER_PAGE) .offset((page - 1) * CATEGORIES_PER_PAGE) + elsif page > 1 + # Pagination is supported only when lazy load is enabled. If it is not, + # everything is returned on page 1. + query = query.none end query = diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rb index e27d9520046..3550fceee2b 100644 --- a/spec/requests/categories_controller_spec.rb +++ b/spec/requests/categories_controller_spec.rb @@ -397,6 +397,35 @@ RSpec.describe CategoriesController do response.parsed_body["category_list"]["categories"].map { |x| x["id"] }, ).not_to include(uncategorized.id) end + + describe "with page" do + before { sign_in(admin) } + + let!(:category2) { Fabricate(:category, user: admin) } + let!(:category3) { Fabricate(:category, user: admin) } + + it "paginates results wihen lazy_load_categories is enabled" do + SiteSetting.lazy_load_categories_groups = "#{Group::AUTO_GROUPS[:everyone]}" + + stub_const(CategoryList, "CATEGORIES_PER_PAGE", 2) { get "/categories.json?page=1" } + expect(response.status).to eq(200) + expect(response.parsed_body["category_list"]["categories"].count).to eq(2) + + stub_const(CategoryList, "CATEGORIES_PER_PAGE", 2) { get "/categories.json?page=2" } + expect(response.status).to eq(200) + expect(response.parsed_body["category_list"]["categories"].count).to eq(2) + end + + it "does not paginate results when lazy_load_categories is disabled" do + stub_const(CategoryList, "CATEGORIES_PER_PAGE", 2) { get "/categories.json?page=1" } + expect(response.status).to eq(200) + expect(response.parsed_body["category_list"]["categories"].count).to eq(4) + + stub_const(CategoryList, "CATEGORIES_PER_PAGE", 2) { get "/categories.json?page=2" } + expect(response.status).to eq(200) + expect(response.parsed_body["category_list"]["categories"].count).to eq(0) + end + end end describe "extensibility event" do